2012-10-05 53 views
3

我有这个类Variables它有多个成员,其中一个叫Name这是一个字符串。假设我有一个List<Variables>。这有NamesX,Y,Y,ZLiNQ有不同的结果

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

问题:为什么_totalCount回报2这是我想要的),而_totalCount2回报4

+3

试着用'.Where'更换'.Select'。 – 3aw5TZetdf

回答

7

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

过滤与Where方法,需要一个谓词完成:

int _totalCount2 = variableList.Where(x => x.Name == variableName).Count(); 
+0

哦,我的坏,所以我会做什么,使其返回'2'? – SkyDrive

+0

谢谢!但现在我有另一个问题。当我在两个linq'.Distinct()。Count();'上添加'Distinct'时,第一个显示1,第二个显示2。为什么它不起作用? – SkyDrive

+0

@DerekFloss这是因为你的第一个例子除了过滤之外还有一个投影。在'Distinct'之前添加'Select(x => x.Name)'去除重复的名字。 – dasblinkenlight