Bone
Bone

Reputation: 907

How to check if there are multiple of the same values in an array

Say I have an array which has the following values

A B A A B C

How do I run a code which will increment the integer variables a, b, and c according to the amount of the times they occur in the array

Upvotes: 0

Views: 1067

Answers (2)

Dave Bish
Dave Bish

Reputation: 19656

You can use GroupBy:

var array = new string[] {"A", "B", "A", "A", "B", "C" };

var counts = array
    .GroupBy(letter => letter)
    .Select(g => new { Letter = g.Key, Count = g.Count() });

If you want to get the counts individually, you can put everything into a dictionary

var countsDictionary = array
    .GroupBy(letter => letter)
    .ToDictionary(g => g.Key, g => g.Count());

var aCount = countsDictionary["A"];
var bCount = countsDictionary["B"];
//etc...

Upvotes: 7

Lukos
Lukos

Reputation: 1852

Look at the example at the bottom of https://msdn.microsoft.com/en-us/library/vstudio/bb535181%28v=vs.100%29.aspx

It basically does what you need.

var array = new string[] {"A", "B", "A", "A", "B", "C" };
int a = array.Count(p => p == "A");

Upvotes: 0

Related Questions