左侧对象不是一行中的null运算符

问题描述 投票:0回答:1

我有此代码使用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:分配的左侧不能包含空传播运算符

c# linq
1个回答
0
投票

您可以将此simplay封装到一个函数中,然后将其用作单行代码。

private static void SetCountToOneIfExists(this IEnumerable<Foo> items, int Id)
{
    var item = items.FirstOrDefault(i => i.Id == 1);
    if(item != null)
       item.Bar = 1;
}

items.SetCountToOneIfExists(1);

在我的示例中,我使用了一种保留方法,您也可以使用普通方法(private void SetCountToOneIfExists(IEnumerable<Foo> items, int Id))。

如果该项目不存在或如何处理这是另一回事,那该死的人应该抛出一个异常。

© www.soinside.com 2019 - 2024. All rights reserved.