号外号外: 原[图享网]更名为 码友网(codedefault.com) 啦,感谢大家一路上的陪伴与支持。代码的世界里,码友网与大家一起同行!

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

.NET 作者: Rector 620阅读 0评论 0收藏 收藏本文

郑重申明:本文未经许可,禁止任何形式转载

.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中如何找出在一个集合List<>中但不在另一个集合List<>中的所有元素集合?

发布于: 2018-01-12 09:04:21
分享扩散:

文章评论

获取验证码