检查 where 子句中的可枚举列表是否为空

本文关键字:列表 是否 枚举 where 子句 检查 | 更新日期: 2023-09-27 18:31:06

        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 是否为空,然后再查看它是否等于分数?

检查 where 子句中的可枚举列表是否为空

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);
}

没有三元运算符,只有 &&-运算符:

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);
}