Short question about the code below. Why does it always display 0?
List<string> strList = new List<string>() { "Yes", "No", "Yes", "No", "Yes", "Yes"};
int hitCount = 0;
strList.Select(i =>
{
if(i.Equals("Yes"))
{
hitCount++;
}
return i;
});
Console.WriteLine(hitCount); // always returns 0.
Console.Read();
Basically in your case query is not running, its just a simple Select
and retrun
, either you have to add ToList()
at the end of query to run query actually or you can do something else to run items having value Yes
. Using Count
is much faster in this case.
int hitcount = strList.Count(p => p == "Yes");
Or use can use Where
clause and Count
hitcount = strList.Where(p => p == "Yes").Count();