使用LINQ获得一个名单,其中项目;>中不在另一个列表<> [英] Use LINQ to get items in one List<>, that are not in another List<>

查看:99
本文介绍了使用LINQ获得一个名单,其中项目;>中不在另一个列表<>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会假设有一个简单的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));
 

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

这篇关于使用LINQ获得一个名单,其中项目;&gt;中不在另一个列表&LT;&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆