首页 / .NET / 正文

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

2755 发布于: 2018-01-29 读完约需5分钟

问题描述

比如有如下的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#程序开发中使用LINQ从一个集合(List<T>)中查询一个元素有哪些方法?

下一篇: [RestSharp].NET/C#程序开发中当使用RestSharp时如何设置请求头内容(content-type)为xml格式?

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

分享扩散:

发表评论

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