Get item count of a list<> using Linq

Geeth picture Geeth · Oct 4, 2010 · Viewed 70.1k times · Source

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;

Answer

Ani picture Ani · Oct 4, 2010
 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.