Count number of given object in a list with LINQ

Posted by Aaginor on Stack Overflow See other posts from Stack Overflow or by Aaginor
Published on 2011-06-20T09:08:57Z Indexed on 2011/06/20 16:22 UTC
Read the original article Hit count: 169

Filed under:
|
|

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

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ