Question

I am trying to filter an IEnumerable object of the duplicate values, so I would like to get the distinct values from it, for example, lets say that it holds 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?

Was it helpful?

Solution

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

Dictionary will use a hash table to hold keys therefore 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) lookups).

OTHER TIPS

Make another IEnumerable. Sort the original. For each item in the original, if the new one doesn't contain the old one, add it.

Another alternative is to use HashSet<T> - a HashSet doesn't allow duplicate items to be used and doesn't require a key/value pair.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top