So here's what I need to do... I have a set of results, and I need to tally how many times each result appears. If I were in PHP I would use a string indexed array, but I just don't know what kind of relatively elegant solution I can do in C#. I'm running through the results in a foreach loop. I've created a custom little class just to hold the data with, and I'm sure I'll need some kind of collection of them. The members are:
String name
int count
Each time through the loop, I need to search my collection of these and
if I already have one with a given name, increase the count. I just want someone to tell me there's a better way of doing this than ANOTHER foreach loop to loop through all the elements of the collection to compare the Strings to see if it exists already, cause that's about all I can think of. I'm pretty new to C#.
Any ideas are much appreaciated, thank you!
Joshua
Loading
Scott LyslePosted May 17, 2008, 2:26 AM
Take a look at linq to objects; you can query your collection and get a count using that easy enough. For example; if you had a collection of monkeys maintained in a typed list (e.g., List() where MonkeyData is a class containing information about each monkey in the collection, and you wanted to get a count of the number of monkeys with names beginning with the letter 'C', you could run something like this against the collection:
MessageBox.Show(monkeys.Count.ToString(), "Total Monkeys");
var cWords = from monkey in monkeys
where monkey.MonkeyName.StartsWith("C")
select monkey;
MessageBox.Show(cWords.Count<BirdData>().ToString(), "Monkeys Starting with C");
In this case, if there were two monkeys named Carl and Candice out of 12 monkeys, the first message box would report a total of 12 monkeys while the second would report that there were two monkeys with names beginning with the letter C.