使用LINQ获得一个名单,其中项目;>中不在另一个列表<>名单、项目、列表、LINQ

2023-09-07 01:27:38 作者:丿老衲灬法号乱来

我会假设有一个简单的LINQ查询要做到这一点,我只是不完全知道如何。请参见下面的code段,注释解释了什么是我想要做的:

 类节目
{
    静态无效的主要(字串[] args)
    {
        名单<人> peopleList1 =新的名单,其中,人物>();
        peopleList1.Add(新的Person(){n = 1});
        peopleList1.Add(新的Person(){n = 2});
        peopleList1.Add(新的Person(){n = 3});

        名单<人> peopleList2 =新的名单,其中,人物>();
        peopleList2.Add(新的Person(){n = 1});
        peopleList2.Add(新的Person(){n = 2});
        peopleList2.Add(新的Person(){n = 3});
        peopleList2.Add(新的Person(){n = 4});
        peopleList2.Add(新的Person(){n = 5});

        //我想执行LINQ查询给我的一切
        //市民对peopleList2'不在'peopleList1
        //这个例子应该给我两个人(ID = 4和ID = 5)
    }
}

类Person
{
    公众诠释ID {获得;组; }
}
 

解决方案

  VAR的结果= peopleList2.Where(P =>!peopleList1.Any(P2 => p2.ID = = p.ID));
 

IDEA 在一个项目里使用另一个项目的类,不是module,是project

I would assume there's a simple LINQ query to do this, I'm just not exactly sure how. Please see code snippet below, the comment explains what I'd like to do:

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

        //I would like to perform a LINQ query to give me all
        //of the people in 'peopleList2' that are not in 'peopleList1'
        //this example should give me two people (ID = 4 & ID = 5)
    }
}

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

解决方案

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