Count number of given object in a list with LINQ
- by Aaginor
I have a list which can contain multiple occurrences of the same object. Now I need to count, how often the given object is contained in this list.
int count = 0;
foreach (IMyObject item in myList)
if (item == object2Count)
count++;
I am sure that this can be done nicer with LINQ, but LINQ is still a mystery to me.
My first question is: How would I count the objects via LINQ and the second question: Will this LINQ version be slower or faster? I am using a ObservableCollection and the number of items in the list is usally rather small ... usally not more then 20.
Thanks in advance,
Frank