C# – Get a list of distinct values in List

cdistinctlinqlist

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.

Best Answer

Notes.Select(x => x.Author).Distinct();

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