LiNQ有不同的结果

Sky*_*ive 3 .net c# linq

我有这个叫Variables有多个成员的类,其中一个叫做Name字符串.假设我有一个List<Variables>.这样做NamesX,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();
Run Code Online (Sandbox Code Playgroud)

问:为什么是_totalCount收益2(这是我想要什么),而_totalCount2回报4

das*_*ght 7

因为Select没有做你认为它做的事情:它是一个投影,而不是一个过滤器.x => x.Name == variableName将为列表中的每个项目计算表达式.你会得到的{False, True, True, False}.然后Count()调用结果调用,返回4.

使用Where带谓词的方法完成过滤:

int _totalCount2 = variableList.Where(x => x.Name == variableName).Count();
Run Code Online (Sandbox Code Playgroud)