7

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

4 Answers 4

15

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.)

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the answer. Now that I see the answer, it seems to be obvious this way :D. As for my predicate, what is weird about it and how would you suggest to write it in an other way?
@Aaginor: If == is using reference equality and you don't store the same instance more than once in the collection count will be 0 or 1. So basically you are determning if object2Count belongs to the collection. There are more efficient ways to determine that using the Any extension method. If on the other hand you have overriden the == operator your predicate is fine.
I do not create a duplicate object to be stored, but store the same reference multiple times. (Like IMyObject o = new MyObject(); myList.Add(o); myList.Add(o);) (Or at least I believe that I do store the same object :D )
@Aaginor: If you want to count how many times a specific reference is stored in the collection your predicate is correct.
1
int count = myList.Count(x => x == object2Count);

Comments

0

Look at 101 LINQ Samples

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

Comments

0

Try this:

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

2 Comments

-1 - this query doesn't return the count of instances of object2Count but the number of objects of class ObjectClass
This is wrong, he's not looking for all objects of a certain class, but for a specific object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.