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
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.)
int count = myList.Count(x => x == object2Count);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With