Distinct

Returns a collection that contains no duplicate entries according to comparer and hashCodeGetter functions.

If an element occurs multiple times in the collection then the later occurrences are discarded.

Internally this method uses a EqualityComparerBuilder<T> object.

Parameter

Returns

Func<T, T, bool> comparer

Func<T, int> hashCodeGetter

IEnumerable<T> source

int

Usage

Discarding duplicate entries

class Product {
    int Id {get; set;}
    string Name {get; set;}
    double Price {get; set;}
}

// products:
// |    Id    |    Name    |    Price    |
// |    1     |  Notebook  |     800     |
// |    2     |    Mouse   |      20     |
// |    3     |   Wallet   |      40     |
// |    4     |    Book    |      10     |
// |    5     | Smartphone |     400     |
// |    1     |  Notebook  |     800     |
// |    1     |  Notebook  |     800     |
// |    4     |    Book    |      10     |

IEnumerable<Product> result = products.Distinct(
    (product1, product2) => product1.Id == product2 == Id,
     product => product.Id.GetHashCode()
    );

// result:
// |    Id    |    Name    |    Price    |
// |    1     |  Notebook  |     800     |
// |    2     |    Mouse   |      20     |
// |    3     |   Wallet   |      40     |
// |    4     |    Book    |      10     |
// |    5     | Smartphone |     400     |

Last updated