LINQ:GROUPBY VS鲜明 [英] Linq: GroupBy vs Distinct

查看:111
本文介绍了LINQ:GROUPBY VS鲜明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图让LINQ查询从集合返回不同的值。我发现两种方法去做;要么使用GROUPBY或DISTINCT。
我知道这分明是为工作做,但我要实现的目标上IEquatable

I've been trying to get a Linq query to return distinct values from a collection. I've found two ways to go about it; either use GroupBy or Distinct. I know that Distinct was made for the job but I have to implement IEquatable on the object.

我试过GROUPBY和工作得很好。我想如果用鲜明VS GROUPBY具有明显的性能优势就知道了。

I tried GroupBy and that worked just fine. I want to know if using Distinct vs GroupBy has a distinct performance advantage.

推荐答案

鲜明的()将在收集比较整个对象(引用类型需要的GetHashCode和等于被覆盖)。它将列举的项目,只是将它们添加到设置。简单,快捷。是这样的:

Distinct() will compare entire objects in collection (for reference types you need GetHashCode and Equals to be overridden). It will enumerate items and just add them to set. Simple and fast. Something like:

Set<TSource> set = new Set<TSource>(comparer);

foreach (TSource tSource in source)
{
     if (!set.Add(tSource))
          continue;

     yield return tSource;
}



GROUPBY()允许您将对象通过一些关键的。在这种情况下,密钥将进行比较。它需要执行的键选择拉姆达在集合中的每个项目。它也将需要为每个不同的密钥分组和集合添加每个项目到组:

GroupBy() allows you to group object by some key. In this case keys will be compared. It will need to execute key selector lambda for each item in collection. Also it will need to create grouping for each distinct key and add each item in collection to its group:

Func<TSource, TElement> elementSelector = x => x;

<TKey, TElement> lookup = new Lookup<TKey, TElement>(comparer);
foreach (TSource tSource in source)
{
     TKey key = keySelector(tSource);

     // simplified pseudo-code
     if (!lookup.Contains(key))
          lookup.Add(new Grouping(key)); 

     lookup[key].Add(elementSelector(tSource));
}

foreach(IGrouping<TKey, TElement> grouping in lookup)
    yield return grouping;



所以,我觉得 GROUPBY()是没有那么快,简单的 DISTICT()

So, I think GroupBy() is not that fast as simple Distict().

这篇关于LINQ:GROUPBY VS鲜明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆