首页 / .NET / 正文

.NET[C#]LINQ中如何找出在一个集合List<>中但不在另一个集合List<>中的所有元素集合?

12857 发布于: 2018-01-12 读完约需8分钟

.NET[C#]LINQ中如何找出在一个集合List<>中但不在另一个集合List<>中的所有元素集合?

问题描述

比如有以下示例程序代码:

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

        //此处需要找出所有在 'peopleList2' 但不在 'peopleList1' 集合中的其他集合
        //此例中应该返回集合对象分别为:ID = 4 , ID = 5
    }
}

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

使用LINQ来做查询,应该如何实现呢?

方案一、Where()

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

方案二、Except()

peopleList2.Except(peopleList1)

方案三、LINQ QUERY

var peopleDifference = 
  from person2 in peopleList2
  where !(
      from person1 in peopleList1 
      select person1.ID
    ).Contains(person2.ID)
  select person2;

方案四

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

方案五

List<string> list1 = new List<string>() { "1", "2", "3" };
List<string> list2 = new List<string>() { "2", "4" };

List<string> inList1ButNotList2 = (from o in list1
                                   join p in list2 on o equals p into t
                                   from od in t.DefaultIfEmpty()
                                   where od == null
                                   select o).ToList<string>();

List<string> inList2ButNotList1 = (from o in list2
                                   join p in list1 on o equals p into t
                                   from od in t.DefaultIfEmpty()
                                   where od == null
                                   select o).ToList<string>();

List<string> inBoth = (from o in list1
                       join p in list2 on o equals p into t
                       from od in t.DefaultIfEmpty()
                       where od != null
                       select od).ToList<string>();

方案六

public static class EnumerableExtensions
{
    public static IEnumerable<TSource> Exclude<TSource, TKey>(this IEnumerable<TSource> source,
    IEnumerable<TSource> exclude, Func<TSource, TKey> keySelector)
    {
       var excludedSet = new HashSet<TKey>(exclude.Select(keySelector));
       return source.Where(item => !excludedSet.Contains(keySelector(item)));
    }
}

调用方法:

list1.Exclude(list2, i => i.ID);

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: .NET[C#]LINQ中如何实现SQL中的LIKE语句查询条件?

下一篇: .NET[C#]LINQ中LEFT OUTER JOIN 如何实现?

本文永久链接码友网 » .NET[C#]LINQ中如何找出在一个集合List<>中但不在另一个集合List<>中的所有元素集合?

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册