C#Null与LINQ合并 [英] C# Null coalesce with LINQ

查看:101
本文介绍了C#Null与LINQ合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个看起来像这样的课程:

I have 2 classes which looks like this:

class Widget
{
    string Selected { get; set; }

    List<Option> Options { get; set; }
}

class Option
{
    string InternalCode { get; set; }

    string ExternalCode { get; set; }
}

每个客户端使用不同的数据动态填充

Options,以便将ExternalCode显示为选项

Options gets populated dynamically with different data per client for showing ExternalCode as options

SelectedExternalCode填充.

然后我需要访问匹配的InternalCode.

I then need to access the InternalCode which matches.

目前我正在这样做:

var option = widget.Options.SingleOrDefault(o => o.ExternalCode == widget.Selected);

var internalCode = option == null ? string.Empty : option.InternalCode;

使用Null Coalesce使用单行是否有可能?

Is this possible using a single line using Null Coalesce?

推荐答案

是的,您可以使用null传播和null合并运算符,如果可以使用C#6,它可以满足您的需求:

Yes, you can use the null propagation and null coalescing operator, which suits your needs if you can use C# 6:

var option = widget.Options
             .SingleOrDefault(o => o.ExternalCode == widget.Selected)?.InternalCode
             ?? string.Empty;

?.将转换为您对option == null ?部分的使用.

The ?. will translate to your use of the option == null ? part.

这篇关于C#Null与LINQ合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆