简体   繁体   中英

Get item count of a list<> using Linq

I want to query a List<> and find out how MANY items match the selection criteria. using LINQ and c# /.net 3.5. How would I modify the query to return an int count.

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. So, you can use your query and access Count() extension method whenever you want.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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