linq unique by property in csharp

To select distinct elements based on one property of an object using LINQ in C#, you can use the Distinct() method with a lambda expression as a parameter.

Assuming a class Person with a Name property, the following snippet would return all unique names:

main.cs
List<Person> people = new List<Person>() {
    new Person { Name = "John", Age = 25 },
    new Person { Name = "Jane", Age = 20 },
    new Person { Name = "John", Age = 30 },
    new Person { Name = "Joe", Age = 25 },
};

var uniqueNames = people.Select(p => p.Name).Distinct();

foreach (var name in uniqueNames) {
    Console.WriteLine(name);
    // Output: John Jane Joe
}
376 chars
14 lines

In this example, we select the Name property of each Person object using the Select() method, and then call Distinct() on the resulting sequence to get only unique names.

gistlibby LogSnag