Essential C# LINQ Queries  Suggest an edit

Distinct

Returns unique values from an IEnumerable. Uniqueness is determined using the default equality comparer.

int[] array = { 1, 2, 3, 4, 2, 5, 3, 1, 2 };

var distinct = array.Distinct();
// distinct = { 1, 2, 3, 4, 5 }

To compare a custom data type, we need to implement the IEquatable interface and provide GetHashCode and Equals methods for the type. Or the equality comparer may be overridden:

class SSNEqualityComparer : IEqualityComparer<Person> {
    public bool Equals(Person a, Person b) => return a.SSN == b.SSN;
    public int GetHashCode(Person p) => p.SSN;
}

List<Person> people;

distinct = people.Distinct(SSNEqualityComparer);


Table Of Contents
22 Enum
25 GUID
65 LINQ Queries
107 Stream
108 Timers
  ↑ ↓ to navigate     ↵ to select     Esc to close