[LINQ].NET/C#程序开中从集合List<T>中获取重复元素的方法有哪些呢?

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

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

问题描述

比如有如下的List<string>字符串集合:

List<String> list = new List<String>{"6","1","2","4","6","5","1"};

现在需要从这个字符串中查询出重复的元素,比如本示例中应该返回的重复元素为 {"6","1"}
使用LINQ查询表达式或者Lambda表达式应该如何实现呢?

方案一

使用LINQGroupBy方法:

var duplicates = lst.GroupBy(s => s)
    .SelectMany(grp => grp.Skip(1));

方案二

List<String> duplicates = lst.GroupBy(x => x)
                             .Where(g => g.Count() > 1)
                             .Select(g => g.Key)
                             .ToList();

方案三

var list = new List<string> { "6", "1", "2", "4", "6", "5", "1" };

var set = new HashSet<string>();
var duplicates = list.Where(x => !set.Add(x));

方案四

var duplicates = list
    .GroupBy( x => x )
    .Where( g => g.Skip(1).Any() )
    .SelectMany( g => g );

方案五

public static IEnumerable<T> Duplicates<T>
         (this IEnumerable<T> source, bool distinct = true)
{
     if (source == null)
     {
        throw new ArgumentNullException("source");
     }

     IEnumerable<T> result = source.GroupBy(a => a).SelectMany(a => a.Skip(1));

     if (distinct == true)
     {
        result = result.Distinct();
     }

     return result;
}

方案六

  List<String> list = new List<String> { "6", "1", "2", "4", "6", "5", "1" };

    var q = from s in list
            group s by s into g
            where g.Count() > 1
            select g.First();

    foreach (var item in q)
    {
        Console.WriteLine(item);

    }

阅读了该文章的人还浏览了...

本文永久链接图享网 » [LINQ].NET/C#程序开中从集合List<T>中获取重复元素的方法有哪些呢?

发布于: 2018-01-29 22:36:01
分享扩散:

文章评论

获取验证码