使用LINQ从一个List<>中获取不在另一个List<>中的项

724

我认为有一个简单的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 });

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

class Person
{
    public int ID { get; set; }
}

我希望执行一个LINQ查询,以便给出所有在peopleList2中但不在peopleList1中的人。

这个例子应该给我两个人(ID = 4 和 ID = 5)。


3
将ID设置为只读可能是个好主意,因为一个对象的身份标识在其生命周期内不应该改变。当然,除非你的测试或ORM框架要求它是可变的。 - CodesInChaos
3
根据这个图表,我们能称之为“左 (或右) 排除连接”吗? - Nate Anderson
11个回答

-1
{
    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 });

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

    var leftPeeps = peopleList2.Where(x => !peopleList1.Select(y => y.ID).Contains(x.ID))?.ToList() ?? new List<Person>();
}

class Person
{
    public int ID { get; set; }
}

请注意!peopleList1.Select(y => y.ID).Contains(x.ID)选择语句。这使我们能够获取我们想要的索引器(ID),并查看它是否包含前一个列表的ID。!表示我们不想要那些。这可能会导致我们没有任何条目。因此,我们可以通过检查null并使用null合并来确保我们有一些内容。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接