Reputation: 907
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
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
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