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
You can use the group clause in C# to do this.
List stuff = new List();
...
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
:
var dictionary = groups.ToDictionary(g => g.Stuff, g => g.Count);