Fastest way to count a collection whilst applying criteria
I have a dictionary that i have already loaded form the database which contains a customer oject key and a Status value which is an Enum. What I would like to do is to count all the items in the dictionary which have a status of a certain enum type ie "Sent". What would be the best way to go about this without going back to the database,开发者_Go百科 or do i have to go back to the database? I dont really want to loop round the whole collection. I cant use linq as im currently using .Net 2.0
public Dictionary<Customer, Status> DistributionList
Many thanks in advance.
If you need a count of elements in the dictionary with the specific value, you can't avoid looping though the list:
int count = 0;
foreach(KeyValuePair<Customer,Status> kvp in DistributionList) {
if(kvp.Value == Status.Sent) count++;
}
Could you use a lambda function? e.g.:
using System.Linq;
int sentCount = DistributionList.Values.Count(s => s.Status == sent);
精彩评论