2012-08-26 86 views
1

有人可以帮我添加下面代码段中评论的if语句吗?如何在LINQ语句中添加if语句

Dictionary<string,int> toReturn; 
List<string> lookup = GetIt(); 

foreach (string test in lookup) 
{ 
    var testDictionary = ToGroupDictionary(test); 
    testDictionary.Keys.ToList().ForEach(k => 
     //if(true){add toReturn list} 
    ); 
} 
+0

你会更好只使用一个'foreach'环 - ['.ForEach '实际上是一个弃用的构造](http://stackoverflow.com/questions/10299458/is-the-listt-foreach-extension-method-gone)。 –

回答

4

只需要添加花括号:

testDictionary.Keys.ToList().ForEach(k => 
{ 
    //if(true){add toReturn list} 
}); 
+1

谢谢Gabe,我很感激帮助。 – Rod

+0

@Rod,没问题 – Gabe

3

或者添加Where条款

testDictionary 
    .Keys 
    .Where(k => conditional(k)) 
    .ForEach(k => { /* something else */ }); 
+1

“ForEach”除外 - “IEnumerable ”不支持该扩展名。在这种情况下你确实需要'ToList'。 – Enigmativity

+0

*叹*这就是为什么我们不经过仔细检查就不能开口。注意,虽然这是有道理的(我知道有一个原因,我不是很熟悉'ForEach'扩展),这为_why_提供了一个很好的理由 - 它不支持该方法 - http://blogs.msdn的.com/b/ericlippert /存档/ 2009/05/18 /的foreach-VS-foreach.aspx –