mexman3217
mexman3217

Reputation: 13

How to show all values that repeat in an array.

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

Answers (5)

serdar
serdar

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 KeyValuePairs are counts.

Upvotes: 0

RaphM
RaphM

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

Seminda
Seminda

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

BudBrot
BudBrot

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

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

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

Related Questions