LINQ Null返回0

时间:2016-04-22 17:40:57

标签: c# .net linq nullable

我有以下LINQ查询。要检入传入值为null,我使用?(例如:<decimal?>)。即使值为null,这也允许查询继续。但是,如何返回0,而不是返回空值?我在我的代码中使用下游的这些值,如果为null,则抛出错误。

var query = referenceDt.AsEnumerable()
    .Where(results => comp(results.Field<decimal?>("OFR_Percent"), ofrPercent) &&
                      results.Field<int?>("ComputeEmptyNodeCount") <= nodeCount)
    .OrderBy(results => results.Field<string>("Cluster"))
    .Select(results => new
    {
        ServerGroup= results.Field<string>("Cluster"),
        OOS_Percent = results.Field<decimal?>("OOS_Percent"),
        OutOfServiceCores = results.Field<int?>("OutOfServiceCores"),
        OFR_Percent = results.Field<decimal>("OFR_Percent"),
        OFR_Count = results.Field<int>("OutForRepairNodeCount"),
        RawTotalNodes = results.Field<int>("RawTotalNodes")
    });

1 个答案:

答案 0 :(得分:3)

您可以使用null-coalescing operator(??)运算符。如果它不为null,则返回左操作数,否则返回右操作数。

.Select(results => new
{
    ServerGroup= results.Field<string>("Cluster") ?? "",
    OOS_Percent = results.Field<decimal?>("OOS_Percent")?? 0,
    OutOfServiceCores = results.Field<int?>("OutOfServiceCores") ?? 0,
    OFR_Percent = results.Field<decimal>("OFR_Percent"),
    OFR_Count = results.Field<int>("OutForRepairNodeCount"),
    RawTotalNodes = results.Field<int>("RawTotalNodes")
});