使用 LINQ 获取一个 List<> 中的项目,这些项目位于另一个 List<> 中

ksg*_*ksg 4 c# linq

我认为有一个简单的 LINQ 查询可以做到这一点,我只是不确定如何。请参阅下面的代码片段,评论解释了我想做的事情:

class Program
{
  static void Main(string[] args)
  {
    List<Person> peopleList1 = new List<Person>();
    peopleList1.Add(new Person() { ID = 1 });
    peopleList1.Add(new Person() { ID = 2 });
    peopleList1.Add(new Person() { ID = 3 });
    peopleList1.Add(new Person() { ID = 4});
    peopleList1.Add(new Person() { ID = 5});

    List<Person> peopleList2 = new List<Person>();
    peopleList2.Add(new Person() { ID = 1 });
    peopleList2.Add(new Person() { ID = 4});


    //I would like to perform a LINQ query to give me only
    //those people in 'peopleList1' that are in 'peopleList2'
    //this example should give me two people (ID = 1& ID = 4)
  }
}


  class Person
  {
     public int ID { get; set; }
  }
Run Code Online (Sandbox Code Playgroud)

Cla*_*ius 10

var result = peopleList2.Where(p => peopleList1.Any(p2 => p2.ID == p.ID));


Ren*_*ogt 6

您可以使用Where以下方法执行此操作:

var result = peopleList1.Where(p => peopleList2.Any(p2 => p2.ID == p.ID));
Run Code Online (Sandbox Code Playgroud)

您也可以使用Intersect( var result = peopleList1.Intersect(peopleList2);),但这需要您以将具有相同的两个实例视为相等的方式来实现额外的IEqualityComparer<Person>或覆盖PersonEqualsGetHashCode方法。否则将执行引用相等。PersonIDIntersect


Tim*_*ter 5

我会通过 ID 加入这两个列表:

var inboth = from p1 in peopleList1
             join p2 in peopleList2
             on p1.ID equals p2.ID
             select p1;
List<Person> joinedList = inboth.ToList();
Run Code Online (Sandbox Code Playgroud)

相关:为什么 LINQ JOIN 比 WHERE 链接快得多?

如果您要覆盖Equals+GetHashCode您可以使用Intersect

List<Person> joinedList = peopleList1.Intersect(peopleList2).ToList();
Run Code Online (Sandbox Code Playgroud)

或者您可以提供自IEqualityComparer<Person>定义Intersect

public class  PersonIdComparer: IEqualityComparer<Person>
{
    public bool Equals(Person x, Person y)
    {
        if(object.ReferenceEquals(x, y)) return true;
        if (x == null || y == null) return false;

        return x.ID == y.ID;
    }

    public int GetHashCode(Person obj)
    {
        return obj == null ? int.MinValue : obj.ID;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在你可以这样使用它:

List<Person> joinedList = peopleList1
     .Intersect(peopleList2, new PersonIdComparer())
     .ToList();
Run Code Online (Sandbox Code Playgroud)

两者Enumerable.JoinEnumerable.Intersect都很有效,因为它们使用的是一组。