Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of given object in a list with LINQ

Tags:

c#

list

linq

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

like image 490
Aaginor Avatar asked Jun 20 '11 09:06

Aaginor


2 Answers

You can easily count objects in a collection using the Count extension method. Either:

var count = myList.Where(item => item == object2Count).Count();

or

var count = myList.Count(item => item == object2Count);

With regards to performance it should be the same as the foreach loop.

(Your predicate item == object2Count looks a bit weird but that is not related to the question about how to count objects in a collection.)

like image 127
Martin Liversage Avatar answered Sep 22 '22 08:09

Martin Liversage


int count = myList.Count(x => x == object2Count);
like image 34
Andy Avatar answered Sep 26 '22 08:09

Andy