问题描述
比如有如下的List<string>字符串集合:
List<String> list = new List<String>{"6","1","2","4","6","5","1"};
现在需要从这个字符串中查询出重复的元素,比如本示例中应该返回的重复元素为 {"6","1"}
使用LINQ
查询表达式或者Lambda
表达式应该如何实现呢?
方案一
使用LINQ
的GroupBy
方法:
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);
}
版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。
发表评论
登录用户才能发表评论, 请 登 录 或者 注册