Finding unique values using the LINQ Distinct operator
November 18, 2016 Leave a comment
Extracting unique values from a sequence of objects in LINQ is very easy using the Distinct operator. It comes in two versions: one with a default equality comparer and another which lets you provide a custom comparer.
We’ll use the following collection for the first demo:
string[] bands = { "ACDC", "Queen", "Aerosmith", "Iron Maiden", "Megadeth", "Metallica", "Cream", "Oasis", "Abba", "Blur", "Chic", "Eurythmics", "Genesis", "INXS", "Midnight Oil", "Kent", "Madness", "Manic Street Preachers"
, "Noir Desir", "The Offspring", "Pink Floyd", "Rammstein", "Red Hot Chili Peppers", "Tears for Fears"
, "Deep Purple", "KISS"};
These are all unique values so let’s create some duplicates:
IEnumerable<string> bandsDuplicated = bands.Concat(bands);