Select Distinct from IEnumerable <T> list in .NET 2.0

I am trying to filter an IEnumerable object from duplicate values, so I would like to get different values ​​from it, for example, you can say that it contains days:

Monday Tuesday Wednesday Wednesday

I would like to filter it and return:

monday tuesday wednesday

What is the most efficient way to do this in .net 2.0?

+1


source to share


3 answers


Dictionary<object, object> list = new Dictionary<object, object>();
foreach (object o in enumerable)
    if (!list.ContainsKey(o))
    {
        // Do the actual work.
        list[o] = null;
    }

      

The dictionary will use a hash table to store the keys, so the lookup is efficient.



Sorting will be O (n log (n)) at best. A hash table with an efficient hash function often outperforms it (O (1) lookup).

+3


source


Make another IEnumerable. Sorts the original. For each element in the original, if the new one does not contain the old one, add it.



+1


source


Another alternative is to use HashSet <T> - HashSet does not allow duplicate elements and does not require a key / value pair.

0


source







All Articles