在一个泛型列表中的ForEach()的Lambda EX pression使用条件运算符?
问题描述:
难道不允许在一个lambda EX pression中的ForEach有条件的经营者?
Is it not allowed to have a conditional operator in a lambda expression in ForEach?
List<string> items = new List<string>{"Item 1", "Item 2", "Item I Care About"};
string whatICareAbout = "";
// doesn't compile :(
items.ForEach(item => item.Contains("I Care About") ?
whatICareAbout += item + "," : whatICareAbout += "");
编译错误 - >只有分配,调用,递增,递减和新对象前pressions可作为一项声明
Compilation error -> "Only assignment, call, increment, decrement, and new object expressions can be used as a statement"
试图用一个正常的,如果不工作或者:
Trying to use a normal if doesn't work either:
// :(
items.ForEach(item => if (item.Contains("I Care About")) {whatICareAbout += item + ", ";}
不可能的?
答
您正在使用较短的形式的拉姆达EX pressions,只允许一个EX pressions。
你需要从长远的形式,它允许多个语句。
You're using the shorter form of lambda expressions, which only allow a single expressions.
You need to the long form, which allows multiple statements.
例如:
items.ForEach(item => {
if (item.Contains("I Care About"))
whatICareAbout += item + ", ";
});