Sometimes we work with collections that contain duplicate data and we just want to iterate over unique values inside the collection. To iterate only through unique values, we generally have to use for-loop and check (compare) each and every data inside the collection for duplicate entries, which is a bit tedious task.
However, if you are using Linq it becomes easier, you have to use just 1 keyword i.e. Distinct().
|
Suppose, we are having an array of string or integer containing few duplicate values, for instance:
int[] duplicateNumbers=new int[]{1,2,2,3,44,4,4,44,4,4,4,33,4,5,7,8,1};
Now we need to iterate through unique numbers only, for that we can write
//a query to iterate over unique numbers only.
var uniqueNumbers = (from num in duplicateNumbers
select num).Distinct();
We are now able to iterate through unique numbers only
Console.WriteLine(“\n Unique Numbers are”);
foreach (int num in uniqueNumbers)
Console.WriteLine(num);
|