开发者

Get item count of a list<> using Linq

开发者 https://www.devze.com 2023-01-18 10:00 出处:网络
I want to query a List<> and find out 开发者_StackOverflow社区how MANY items match the selection criteria.using LINQand c# /.net 3.5.How would I modify the query to return an int count.

I want to query a List<> and find out 开发者_StackOverflow社区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");

This uses an overload of Enumerable.Count that takes aFunc<TSource, bool>predicate to filter the sequence.


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


Just surround your query like this: (from ... select n).Count().

0

精彩评论

暂无评论...
验证码 换一张
取 消