检查where子句中的ienumerable列表是否为null

时间:2014-11-20 13:03:18

标签: c#

        public static int calcValueMS(FPT doc, int score)
        {
            return doc.PositionSection.ManagedStrategyAssets
                      .Where(a => a.AssetRiskData.RiskMeasure.RiskRating.Id == score )                                          
                      .SelectMany(h => h.Holdings).Sum(v => v.CurrentValue);
        }

我的方法返回某些资产的总和值。他们匹配风险评级。有时虽然风险等级Id将为空。我尝试过使用三元运算符,但似乎没有用。

如何首先检查风险评级Id是否为空,然后查看它是否等于分数?

2 个答案:

答案 0 :(得分:1)

没有三元运算符&& -operator:

public static int calcValueMS(FPT doc, int score)
{
        return doc.PositionSection.ManagedStrategyAssets
            .Where(a => a.AssetRiskData.RiskMeasure.RiskRating.Id != null && a.AssetRiskData.RiskMeasure.RiskRating.Id == score )
            .SelectMany(h => h.Holdings)
            .Sum(v => v.CurrentValue);
}

答案 1 :(得分:1)

RiskRating.Id似乎是int?,而不是int,因此您可以使用HasValueValue

您可以在Linq请求中汇总多个Where子句:

public static int calcValueMS(FPT doc, int score)
{
    return doc.PositionSection.ManagedStrategyAssets
              .Where(a => a.AssetRiskData.RiskMeasure.RiskRating.Id.HasValue)
              .Where(a.AssetRiskData.RiskMeasure.RiskRating.Id.Value == score)
              .SelectMany(h => h.Holdings)
              .Sum(v => v.CurrentValue);
}