I really hope you can help me with this: I am currently working with Windows Forms and I need to show in a MessageBox or a Label, all the values that repeat within an array. For example, if my array stores the following numbers: {3, 5, 3, 6, 6, 6, 7} I need to be able to read it and grab and show the ones that repeat themselves, which in this case would be 3 twice and 6 three times... Thanks for your time!
Asked
Active
Viewed 104 times
5 Answers
2
LINQ can be helpfull;
var array = new int[] { 3, 5, 3, 6, 6, 6, 7 };
var counts = array.GroupBy(n => n) // Group by the elements based their values.
.Where(g => g.Count() > 1) // Get's only groups that have value more than one
.Select(k => k.Key) // Get this key values
.ToList();
counts will be List<Int32>
and it's values as 3
and 6
.
If you want to get count values also with their values, take a look at Jon's answer.

Community
- 1
- 1

Soner Gönül
- 97,193
- 102
- 206
- 364
0
The "core" logic of your code may look like the following:
var array = new [] { 3, 5, 3, 6, 6, 6, 7 };
var duplicates = array.Where(number => array.Count(entry => entry == number) > 1).Distinct();
To get the output like in Seminda's example, simply omit the final .Distinct().

RaphM
- 81
- 1
- 5
0
Something like:
var numbers = new int[]{3, 5, 3, 6, 6, 6, 7};
var counterDic = new Dictionary<int,int>();
foreach(var num in numbers)
{
if (!counterDic.ContainsKey(num))
{
counterDic[num] = 1;
}
else
{
counterDic[num] ++;
}
}
Linq would also be a possibility as the others mentioned. But its slow (anyway, performance shouldnt be a decider).

BudBrot
- 1,341
- 2
- 24
- 44
0
if you want to get the result output like {3,3,6,6,6} do like this
int[] my = new int[] { 3, 5, 3, 6, 6, 6, 7 };
//List<int> lst = my.OfType<int>().ToList();
var query = my.GroupBy(x => x)
.Where(g => g.Count() > 1)
.SelectMany(m=>m)
.ToList();

Seminda
- 1,745
- 12
- 15
0
var array = new int[] { 3, 5, 3, 6, 6, 6, 7 };
Dictionary<int, int> counts = array.GroupBy(x => x)
.Where(g => g.Count() > 1)
.ToDictionary(g => g.Key, g => g.Count());
Values of KeyValuePair
s are counts.

serdar
- 1,564
- 1
- 20
- 30