Easy way to get distinct values from a .NET List

Posted on November 25, 2012 by Michael Roma

The follow example shows how to get a list of objects that are distinct based on the Name property. The example groups by name, then select the first object in the list of in that grouping and returns to a new list.

// list definition
public class MyListItem
{
    public string Name { get; set; }
    public string Description { get; set; }
}

// example with myList being an instance of List
myList
    .GroupBy(x => x.Name)
    .Select(x => x.First())
comments powered by Disqus