c# - 左侧对象不是一行中的空运算符

标签 c# linq

我有这段代码可以使用 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

One line declare, compare and return in c#有些相关.

关于c# - 左侧对象不是一行中的空运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58642556/

相关文章:

c# - 使用 LINQ 优化两个列表中的比较

c# - Linq-to-SQL:组合(或运算)多个 "Contains"过滤器?

python - python 中类似 linq 的求和函数

c# - 如何使 LINQ 执行 (SQL) LIKE 范围搜索

c# 4.5 - 一个主要做数据库插入的 TCP 服务器是否应该在一个任务上启动每个客户端

c# - 使用 Objective Sharpie 绑定(bind) CocoaPods 库

c# - 使用目标 :module switch 编译代码

c# - Linq orderby 没有按预期工作

c# - 确定 null 或计数 0 的最佳方法

c# - LINQ 方法的序列有什么重要性吗?