0

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

1
  • as a hint, I'd suggest running a distinct list and use the intersect (or potentially Count()) method thereafter on one list against the other... Commented Jul 3, 2015 at 16:08

2 Answers 2

7

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...
Sign up to request clarification or add additional context in comments.

5 Comments

plus one dave - exactly what I would have suggested (and/or distinct with count)
what if the values aren't letters, but like words.
Why does it need to be that complicated? What's wrong with Enumerable.Count()?
Does the addition of the dictionary method explain it?
@Lukos - That loops over the list n. times - less efficient I'd suggest (depends on the array, though)
0

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");

2 Comments

If you have 10 'letters' you'll have to iterate over the entire list 10 times to get the counts this way
Microseconds in reality, at least that is my assumption without anything to the contrary in the OP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.