Lambda表达式可发现差异 [英] Lambda expression to find difference
本文介绍了Lambda表达式可发现差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
具有以下数据
string[] data = { "a", "a", "b" };
我非常想找到重复项并得到以下结果:
I'd very much like to find duplicates and get this result:
a
我尝试了以下代码
var a = data.Distinct().ToList();
var b = a.Except(a).ToList();
显然这没有用,我可以看到上面发生了什么,但是我不确定如何解决.
obviously this didn't work, I can see what is happening above but I'm not sure how to fix it.
推荐答案
如果运行时没有问题,则可以使用
When runtime is no problem, you could use
var duplicates = data.Where(s => data.Count(t => t == s) > 1).Distinct().ToList();
好旧的O(n ^ n)=)
Good old O(n^n) =)
编辑:现在是一个更好的解决方案. =) 如果您定义新的扩展方法,例如
Now for a better solution. =) If you define a new extension method like
static class Extensions
{
public static IEnumerable<T> Duplicates<T>(this IEnumerable<T> input)
{
HashSet<T> hash = new HashSet<T>();
foreach (T item in input)
{
if (!hash.Contains(item))
{
hash.Add(item);
}
else
{
yield return item;
}
}
}
}
您可以使用
var duplicates = data.Duplicates().Distinct().ToArray();
这篇关于Lambda表达式可发现差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文