[英]HashSet or Distinct to read distinct values of property in List<> of objects
This is in someway related to this ( Getting all unique Items in a C# list ) question. 这在某种程度上与此相关( 获取C#列表中的所有唯一项 )问题。
The above question is talking about a simple array of values though. 上面的问题是谈论一系列简单的价值观。 I have an object returned from a third party web service:
我有一个从第三方Web服务返回的对象:
public class X
{
public Enum y {get; set;}
}
I have a List of these objects List<x> data;
我有一个列表这些对象
List<x> data;
, about 100 records in total but variable. ,总共约100条记录,但可变。 Now I want all the possible values in the list of the property
y
and I want to bind this do a CheckBoxList.DataSource
(in case that makes a difference). 现在我想要属性
y
列表中的所有可能值,并且我想绑定它做一个CheckBoxList.DataSource
(如果有所不同)。
Hows the most efficient way to do this? 这是最有效的方法吗?
I can think of two algorithms: 我可以想到两种算法:
var data = HashSet<Enum> hashSet = new HashSet<Enum>(xs.Select(s => s.y));
chkBoxList.DataSource = data;
Or 要么
var data = xs.Select(s => s.y).Distinct();
chkBoxList.DataSource = data;
My gut feeling is the HashSet but I'm not 100% sure. 我的直觉是HashSet,但我不是百分百肯定。
Open to better ideas if anyone has any idea? 如果有人有任何想法,愿意接受更好的想法?
If it is a one time operation - use . 如果是一次性操作 - 使用。
Distinct
. Distinct
。 If you are going to add elements again and again - use HashSet
如果要
HashSet
添加元素 - 请使用HashSet
The HashSet
one, since it keeps the objects around after the hashset object has been constructed, and foreach-ing it will not require expensive operations. HashSet
一个,因为它在构造hashset对象之后保持对象,并且预处理它不需要昂贵的操作。
On the other hand, the Distinct
enumerator will likely be evaluated every time the DataSource is enumerated, and all the work of removing duplicate values will be repeated. 另一方面,每次枚举DataSource时都可能会评估
Distinct
枚举器,并且将重复删除重复值的所有工作。
Being as their are no better answers coming forward I'm going to answer my own question. 因为他们没有更好的答案,我将回答我自己的问题。 I decided to use a
HashSet
though the performance benefits are possibly marginal for my size of result set. 我决定使用
HashSet
虽然对于我的结果集大小,性能优势可能很小。 When it comes down to it the definition of a HashSet
taken from here was: 归结到它时,从这里获取的
HashSet
的定义是:
HashSet is an unordered collection containing unique elements.
HashSet是一个包含唯一元素的无序集合。
And I wanted an unordered collection of values that were unique . 我想要一个独特的无序值集合 。 (Horses for courses) I also do not require indexing and I only wish to enumerate my set.
(课程的马)我也不需要索引,我只想枚举我的设置。
So it seemed the best fit. 所以它似乎是最合适的。 Marking Staffi as the answer as his was the most informative though.
将Staffi标记为答案,因为他的信息量最大。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.