我有这段代码可以使用 FirstOrDefault()
查找可能存在或不存在的项目:
public class Foo
{
public int Id { get; set; }
public string Bar { get; set; }
}
var items = new List<Foo>
{
new Foo { Id = 1, Bar = "Bar" }
};
var item = items.FirstOrDefault(i => i.Id == 1);
if (item != null)
{
item.Bar = "Baz";
}
有没有办法用最后四行制作一个像这样的单行?
items.FirstOrDefault(i => i.Id == 1)?.Bar = "Baz";
这给出了一个编译器错误:
CS9030: The left-hand side of an assignment cannot contain a null propagating operator
最佳答案
你可以使用 pattern matching缩短它:
if (items.FirstOrDefault(i => i.Id == 1) is Foo f)
{
f.Bar = "Qux";
}
因为当 FirstOrDefault()
返回 null
时取反为 false
。
关于c# - 左侧对象不是一行中的空运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58642556/