Get a list of distinct values in List

Darrel Hoffman picture Darrel Hoffman · Apr 21, 2012 · Viewed 440.7k times · Source

In C#, say I have a class called Note with three String member variables.

public class Note
{
    public string Title;
    public string Author;
    public string Text;
}

And I have a list of type Note:

List<Note> Notes = new List<Note>();

What would be the cleanest way to get a list of all distinct values in the Author column?

I could iterate through the list and add all values that aren't duplicates to another list of strings, but this seems dirty and inefficient. I have a feeling there's some magical Linq construction that'll do this in one line, but I haven't been able to come up with anything.

Answer

Kirk Woll picture Kirk Woll · Apr 21, 2012
Notes.Select(x => x.Author).Distinct();

This will return a sequence (IEnumerable<string>) of Author values -- one per unique value.