Building a dictionary of counts of items in a list
You can use the group clause in C# to do this.
List<string> stuff = new List<string>();
...
var groups =
from s in stuff
group s by s into g
select new {
Stuff = g.Key,
Count = g.Count()
};
You can call the extension methods directly as well if you want:
var groups = stuff
.GroupBy(s => s)
.Select(s => new {
Stuff = s.Key,
Count = s.Count()
});
From here it's a short hop to place it into a Dictionary<string, int>
:
var dictionary = groups.ToDictionary(g => g.Stuff, g => g.Count);
I would have made a specialized List, that backed by the Dictionary and the add method would test for membership and increase count if found.
sorta like:
public class CountingList
{
Dictionary<string, int> countingList = new Dictionary<string, int>();
void Add( string s )
{
if( countingList.ContainsKey( s ))
countingList[ s ] ++;
else
countingList.Add( s, 1 );
}
}
One idea would be to give the dictionary a default value of zero, so you wouldn't have to special case the first occurrence.