2014-02-07 4 views
0

다음 코드에서는 그룹화 대상을 결정하는 특정 속성을 기반으로 두 개의 목록을 만듭니다. 그런 다음 두 목록을 하나의 목록으로 연결합니다.조건부로 목록 항목 그룹화

var naFundCodeGroups = (from sar in aidItems  
          where sar.SuFundCode.Substring(0, 2) != "SA"          
          group sar by sar.NaFundCode into sa 
          select sa).ToList(); 

    var suFundCodeGroups = (from sar in aidItems 
          where sar.SuFundCode.Substring(0, 2) == "SA" 
          group sar by sar.SuFundCode 
          into sa 
          select sa).ToList(); 

    var fundCodeGroups = naFundCodeGroups.Concat(suFundCodeGroups).ToList(); 

더 세련된 방법이 있습니까?
예를 들어 조건문을 사용하여 그룹을 단일 명령문에서 어떻게 든 만들 수 있습니다.

감사합니다. IMO,

var fundCodeGroups = (from sar in aidItems 
    group sar by (sar.SuFundCode.Substring(0, 2) == "SA" ? 
     sar.SuFundCode : sar.NaFundCode) 
    into sa 
    select sa).ToList(); 

또는 가독성을 더 컴팩트를 사용하여 (이 경우 : SuFundCode하고 쿼리 이해 구문을 고집 NaFundCode의 세트 사이에 공통의 가치가없는 경우

+0

나는 성명서에서 같은 것을 얻을 수 있다고 생각하지 않는다. –

답변

1

이 작동합니다) 유창/람다 구문 :

var fundCodeGroups = aidItems 
    .GroupBy(sar => sar.SuFundCode.Substring(0, 2) == "SA" ? 
     sar.SuFundCode : sar.NaFundCode) 
    .ToList(); 

그렇지 않으면, 이들의 작동합니다, 원본으로 그룹화의 마지막 반환하지만 같은 종류 :

var fundCodeGroups1 = (from sar in aidItems 
    group sar by new { IsSA = sar.SuFundCode.Substring(0, 2) == "SA", 
     Code = (sar.SuFundCode.Substring(0, 2) == "SA" ? sar.SuFundCode : sar.NaFundCode) } 
    into sa 
    select sa).ToList(); 

var fundCodeGroups2 = aidItems 
    .GroupBy(sar => new { IsSA = sar.SuFundCode.Substring(0, 2) == "SA", 
     Code = (sar.SuFundCode.Substring(0, 2) == "SA" ? sar.SuFundCode : sar.NaFundCode) }) 
    .ToList(); 

var fundCodeGroups3 = aidItems 
    .GroupBy(sar => sar.SuFundCode.Substring(0, 2) == "SA") 
    .SelectMany(g => g.Key ? g.GroupBy(i => i.SuFundCode) : g.GroupBy(i => i.NaFundCode)) 
    .ToList(); 

이 중 어떤 것이 원래 솔루션보다 더 선명하거나 성능이 좋을지 확신하지 못합니다.