2013-05-08 65 views
2

我知道这个工程:选择所有的Lambda凡()

var result = someCollection.Select(x=>x); 

Where()方法类似的结果后,我:

var result = someCollection.Where(x=> someBool ? x : x.Key == 1); 

我想选择“一切”如果someBool为真。上面的代码不起作用。有什么办法可以解决这个使用lambda?

+1

不知道你想要什么。也许'someBool || x.Key == 1'。 – CodesInChaos 2013-05-08 07:56:35

+0

下面的答案是可行的,但是你可以在if语句中添加where子句吗(即,如果'someBool'为true,那么不会添加它)? – 2013-05-08 08:13:20

+1

这是什么linq提供程序?如果它是'Linq-To-Objects',你应该考虑为'someBool'使用一个简单的'if'子句。否则,即使你知道你想要所有的东西,你仍然在循环整个系列。 – 2013-05-08 08:31:30

回答

4

使用||运营商,如果someBool是真实的,它会选择所有的记录。

var result = someCollection.Where(x=> someBool || x.Key == 1); 
4

您正在寻找的conditional- OR操作

var result = someCollection.Where(x => someBool || x.Key == 1); 
1

这是测试的代码

var result = someCollection.Where(x => someBool || x.Key == 1); 
+0

我没有看到你的帖子我有我自己的尝试和张贴我看到一些民族也分享same.You也是正确的 – 2013-05-08 08:32:05

1

作为替代使用||Where的断言它有时有用如果需要的话,只应用Where

var result = source; 
if(!someBool) 
    result = result.Where(x => x.Key == 1); 

这通常是一个快一点,因为它并不需要在所有的过滤。但它暴露source到外面,这有时是不受欢迎的。

+0

+1,我喜欢这个自己,如果没有很好的理由不发布后它。但是这样做。 (这是一个耻辱'AsEnumerable'在这里没有帮助。) – Rawling 2013-05-08 08:33:05

1

你可以做交替,

var result = someCollection; 

if (someBool) 
{ 
    result = someCollection.Where(x => x.Key == 1); 
} 

我觉得额外的输入提高了代码的可读性和可提高性能。