Distinct and Contains
Learn to deduplicate with Distinct and check membership with Contains.
Deduplication with Distinct
The Distinct method removes duplicate elements from a collection; each value appears only once. new[] { 1, 2, 2, 3, 3, 3 }.Distinct() yields { 1, 2, 3 }. Equality is checked with the default Equals.
When you need a custom equality comparer, the Distinct(comparer) overload is available. The result is again an IEnumerable<T>; order is preserved: the first occurrence of each value is kept.
Membership with Contains
The Contains method asks whether the collection includes a specific value. numbers.Contains(7) checks whether 7 is in the array and returns bool. This is shorter and clearer than numbers.Any(n => n == 7).
Contains uses Equals by default for reference types. For custom equality there is a Contains(value, comparer) overload. Lists do a linear search with Contains; for large data, membership on a HashSet<T> is faster.
Exercise Print distinct numbers
Remove duplicates from the numbers array with Distinct and print each in a foreach loop.
Show example solution
Dedupe with numbers.Distinct(), loop with foreach, print with Console.WriteLine(n).
Example solution:
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] numbers = { 1, 2, 2, 3, 3, 3 };
foreach (var n in numbers.Distinct())
{
Console.WriteLine(n);
}
}
}
Test yourself
-
Match the Distinct result
- {1,2,2,3}
- {1,2,3}
- {a,a,b}
- {a,b}
- {5,5,5}
- {5}
- {x,y}
- {x,y}
-
Complete the Contains call
bool has = numbers.____(7);Show answer
bool has = numbers.Contains(7); -
What does Distinct return?
new[] { 4, 4, 5, 5 }.Distinct()- int (a number)
- bool
- IEnumerable<int>
- List<int>
Show answer
List<int> — Correct. Distinct returns IEnumerable<int>; it is a deferred query. Convert with ToList if needed.