I have this class called Variables which has multiple members and one of it is called Name which is a string. Supposed I have a List<Variables>. This has Namesof X, Y, Y, Z.
string variableName = 'Y';
int _totalCount = (from p in variableList
where p.Name == variableName
select p.Name).Count();
int _totalCount2 = variableList.Select(x => x.Name == variableName).Count();
Question: Why is _totalCount returns 2 (which is what I want) while _totalCount2 returns 4?
Because
Selectis not doing what you think it does: it’s a projection, not a filter.The expression
x => x.Name == variableNameis calculated for each item on your list. You’ll get{False, True, True, False}. Then theCount()gets called on the result, returning4.Filtering is done with the
Wheremethod that takes a predicate: