2014-11-20 4 views
0
 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은 null이되지만. 삼항 연산자를 사용해 보았지만 작동하지 않는 것 같습니다.ienumerable 목록이 where 절에서 null인지 확인하십시오.

위험 등급 ID가 Null인지 먼저 확인한 다음 점수와 동일한 지 확인하십시오.

+1

당신이 명시 적으로 확인하려는 이유는 무엇입니까? ID가 실제로'null'인지 'RiskRating' 객체입니까? – Dirk

답변

1

RiskRating.Idint? 아닌 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); 
} 
+0

이 게시물이 질문에 대답하는 동안 추가 검사 ('Id.HasValue')가'Id == score'에 중복되므로 원래 코드에 아무 것도 추가하지 않는다는 점에 유의해야합니다. – Dirk

1

이 단지 & & - 연산자에는 삼항 연산자에게 없다 :

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

null 가능성이있는'int' /'long' 가능성이 있기 때문에 좀 더 깔끔한 코드를 위해'a.AssetRiskData.RiskMeasure.RiskRating.Id.HasValue'를 할 수 있습니다. – krillgar

+2

'Id'가'null'이라면 두번째 검사 ('Id == score')도'false'를 반환합니다. – Dirk

관련 문제