HashSet or Distinct to read distinct values of property in List<> of objects

本小妞迷上赌 提交于 2019-12-04 04:42:00

问题


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?


回答1:


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.




回答2:


If it is a one time operation - use .Distinct. If you are going to add elements again and again - use HashSet




回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!