I have a List containing a bunch of strings that can occur more than once. I would like to take this list and build a dictionary of the list items as the key and the count of their occurrences as the value.
Example:
List<string> stuff = new List<string>(); stuff.Add( 'Peanut Butter' ); stuff.Add( 'Jam' ); stuff.Add( 'Food' ); stuff.Add( 'Snacks' ); stuff.Add( 'Philosophy' ); stuff.Add( 'Peanut Butter' ); stuff.Add( 'Jam' ); stuff.Add( 'Food' );
and the result would be a Dictionary containing:
'Peanut Butter', 2 'Jam', 2 'Food', 2 'Snacks', 1 'Philosophy', 1
I have a way to do this, but it doesn’t seem like I’m utilizing the good stuff in C# 3.0
public Dictionary<string, int> CountStuff( IList<string> stuffList ) { Dictionary<string, int> stuffCount = new Dictionary<string, int>(); foreach (string stuff in stuffList) { //initialize or increment the count for this item if (stuffCount.ContainsKey( stuff )) { stuffCount[stuff]++; } else { stuffCount.Add( stuff, 1 ); } } return stuffCount; }
You can use the group clause in C# to do this.
You can call the extension methods directly as well if you want:
From here it’s a short hop to place it into a
Dictionary<string, int>: