4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

2つの配列両方に属するものを取得する方法をLINQで

Last updated at Posted at 2015-06-08

#2つの配列のクラスが同じ場合


public class Student
{
    public string Name;
    public int Age;
}

public class Class
{
    public Student[] Students;
}

public class Club
{
    public Student[] Students;
}

クラスとクラブ両方に属している生徒の名前のリストを作りたい場合
foreachを使った場合は

var names = new List<string>();
foreach (var student in @class.Students)
{
    foreach (var clubStudent in club.Students)
    {
        if (student == clubStudent)
        {
            names.Add(student.Name);
        }
    }
}

LINQなら

var names = @class.Students
    .Intersect(club.Students)
    .ToList();

#2つの配列が同じクラスではない場合


public class Student
{
    public string Name;
    public int Age;
}

public class Class
{
    public Student[] Students;
}

public class Member
{
    public int Id;
    public string Name;
}

public class Club
{
    public Member[] Members;
}

クラスとクラブ両方に属している同じ名前の人のメンバーIDリストを作りたい場合
foreachを使った場合は


var ids = new List<int>();
foreach (var student in @class.Students)
{
    foreach (var member in club.Members)
    {
        if (student.Name == member.Name)
        {
            ids.Add(member.Id);
        }
    }
}

LINQなら


var ids = @class.Students
    .Join(club.Members, student => student.Name, member => member.Name, (student, member) => member.Id)
    .ToList();
4
5
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?