Calculate the number of a given object in a list using LINQ

I have a list that can contain multiple occurrences of the same object. Now I need to calculate how often this object is contained in this list.

int count = 0; foreach (IMyObject item in myList) if (item == object2Count) count++; 

I'm sure this can be done better with LINQ, but LINQ is still a mystery to me.

My first question is: how do I count objects through LINQ and the second question is: will this version of LINQ be slower or faster? I use ObservableCollection, and the number of items in the list is usually quite small ... usually no more than 20.

Thanks in advance,
Franc

+6
source share
4 answers

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

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

or

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

In terms of performance, it should be the same as the foreach .

(Your predicate item == object2Count looks a bit odd, but that doesn't have to do with the question of how to count objects in a collection.)

+10
source
 int count = myList.Count(x => x == object2Count); 
+1
source

Try the following:

 var count = objectlist.Count(x => x == object2Count)); 
0
source

Look at 101 LINQ Samples

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

0
source

Source: https://habr.com/ru/post/890907/


All Articles