用LINQ计数列表中给定对象的数量 [英] Count number of given object in a list with LINQ

查看:65
本文介绍了用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++;

我确信使用LINQ可以更好地完成此操作,但是LINQ对我来说仍然是个谜.

I am sure that this can be done nicer with LINQ, but LINQ is still a mystery to me.

我的第一个问题是:我如何通过LINQ计数对象,第二个问题:此LINQ版本会变慢还是变快?我使用的是ObservableCollection,列表中的项目数通常很小,通常不超过20.

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();

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

关于性能,它应该与 foreach 循环相同.

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

(您的谓词 item == object2Count 看起来有些怪异,但这与有关如何对集合中的对象进行计数的问题无关.)

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

这篇关于用LINQ计数列表中给定对象的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆