Finding unique values from a list of objects

I have several times had to get a unique list of values from a set of objects, for example the simplest way to populate a filter dropdown with possible names of the people in a list of persons. A simple/nifty little routine that does that:

Based on an list (IEnumerable<S>) loop through them all, using a delegate get the value/property (of type T) from the object (of class S) and return all uniques hereof (using basic object equality – Equals)

public delegate T ValueDelegate<T, S>(S obj);

public static IEnumerable<T> FindUniques<T, S>(IEnumerable<S> list, ValueDelegate<T, S> valueDelegate)
{
    List<T> result = new List<T>();
    foreach (S item in list)
    {
        T value = valueDelegate(item);
        if (!result.Contains(value))
        {
            result.Add(value);
            yield return value;
        }
    }
}


Follow

Get every new post delivered to your Inbox.