Count number of given object in a list with LINQ

♀尐吖头ヾ 提交于 2020-12-02 10:10:06

问题


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


回答1:


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




回答2:


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



回答3:


Look at 101 LINQ Samples

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




回答4:


Try this:

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


来源:https://stackoverflow.com/questions/6408972/count-number-of-given-object-in-a-list-with-linq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!