Reputation: 13
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!
Upvotes: 0
Views: 106
Reputation: 1628
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.
Upvotes: 0
Reputation: 91
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().
Upvotes: 0
Reputation: 1773
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();
Upvotes: 0
Reputation: 1411
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).
Upvotes: 0
Reputation: 98830
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.
Upvotes: 2