This is in someway related to this (Getting all unique Items in a C# list) question.
The above question is talking about a simple array of values though. I have an object returned from a third party web service:
public class X
{
public Enum y {get; set;}
}
I have a List of these objects List<x> data;
, about 100 records in total but variable. 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).
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.
Open to better ideas if anyone has any idea?
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.
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.
If it is a one time operation - use .Distinct
. If you are going to add elements again and again - use HashSet
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. When it comes down to it the definition of a HashSet
taken from here was:
HashSet is an unordered collection containing unique elements.
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.
来源:https://stackoverflow.com/questions/19296495/hashset-or-distinct-to-read-distinct-values-of-property-in-list-of-objects