简体   繁体   English

使用Linq获取列表<>的项目计数

[英]Get item count of a list<> using Linq

I want to query a List<> and find out how MANY items match the selection criteria. 我想查询List <>并找出MANY项如何与选择条件匹配。 using LINQ and c# /.net 3.5. 使用LINQ和c#/.net 3.5。 How would I modify the query to return an int count. 如何修改查询以返回int计数。

var specialBook = from n in StoreDisplayTypeList 
                  where n.DisplayType=="Special Book" 
                  select n;
 var numSpecialBooks = StoreDisplayTypeList.Count(n => n.DisplayType == "Special Book");

这使用了Enumerable.Count的重载,它使用Func<TSource, bool>谓词来过滤序列。

Try this: 试试这个:

int specialBookCount = (from n in StoreDisplayTypeList 
                        where n.DisplayType=="Special Book" 
                        select n).Count()

But if you need data as well, you might want to operate with IEnumerable. 但是,如果您还需要数据,则可能需要使用IEnumerable进行操作。 So, you can use your query and access Count() extension method whenever you want. 因此,您可以随时使用查询并访问Count()扩展方法。

var specialBook = from n in StoreDisplayTypeList 
                  where n.DisplayType=="Special Book" 
                  select n;
int num = specialBook.Count();

只需将您的查询包围如下:( (from ... select n).Count()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM