How to remove duplicate values from an array in C# ?

QuestionsCategory: C#How to remove duplicate values from an array in C# ?
Himanshu SHimanshu S asked 6 months ago

Given an integer array how to remove duplicates  value from it and count the occurrence of duplicate values .
Input:

var arr = new [] { 101, 51, 10, 2, 2, 3, 4, 5, 15, 6, 7, 8, 9, 101, 12, 12 };
1 Answers
Best Answer
Mahesh DeshmaneMahesh Deshmane answered 6 months ago

Using Linq – GroupBy:
Groups the elements of a sequence

var arr = new [] { 101, 51, 10, 2, 2, 3, 4, 5, 15, 6, 7, 8, 9, 101, 12, 12 };

var result = arr.GroupBy(v => v);

foreach (var item in result)
    Console.WriteLine("Value {0} has {1} items", item.Key, item.Count());

Without Using Linq

var arr = new [] { 101, 51, 10, 2, 2, 3, 4, 5, 15, 6, 7, 8, 9, 101, 12, 12 };

var dict = new Dictionary<int, int>();

foreach (var value in arr)
{
    if (dict.ContainsKey(value))
        dict[value]++;
    else
        dict[value] = 1;

}

 foreach (var item in dict)
    Console.WriteLine("Item {0} occurred {1} times.", item.Key, item.Value);