2012-08-08 6 views
0

예를 들어 설명해 보겠습니다.Linq를 사용하여 누락 된 레코드 조합 확인

var vProducts = new[] { 
    new { Product = "A", Location ="Y", Month = "January", Demand = 50 }, 
    new { Product = "A", Location ="Y", Month = "February", Demand = 100 }, 
    new { Product = "A", Location ="Y", Month = "March", Demand = 20 }, 
    new { Product = "A", Location ="Y", Month = "June", Demand = 10 } 
}; 

var vPeriods = new[] { 
    new { Priority = 1, Month = "January" }, 
    new { Priority = 2, Month = "February" }, 
    new { Priority = 3, Month = "March" }, 
    new { Priority = 4, Month = "April" }, 
    new { Priority = 5, Month = "May" }, 
    new { Priority = 6, Month = "June" } 
}; 

var vAll = from p in vProducts 
     from t in vPeriods 
     select new 
      { 
      Product = p.Product, 
      Location = p.Location, 
      Period = t.Priority, 
      PeriodName = t.Month, 
      Demand = p.Demand 
      }; 

위 쿼리는 제품 & 기간의 모든 조합을 생성합니다. 그러나 아래에 표시된 것과 같이 일치하는 Month가없는 제품과 함께 모든 제품의 목록을 가져와야합니다. 의견에 대한

예를

Product  Location  Priority  Month Demand 
    A    Y   1   January  50 
    A    Y   2   February 100 
    A    Y   3   March  20 
    A    Y   4   April  null 
    A    Y   5   May   null 
    A    Y   6   June  10 

감사합니다.

+2

제목을 조금 더 좋게 만들 수 있습니까? 현재의 질문은 귀하의 질문을 실제로 설명하지 않습니다. –

+0

내가 할 수있는대로 제목을 업데이트하려고 시도했습니다. – user320587

답변

0

당신은이 같은 갈 것이다하는 left outer join하고 싶지 : 물론

var res = from period in vPeriods 
        join product in vProducts on period.Month equals product.Month into bla 
        from p in bla.DefaultIfEmpty() 
        select new { period.Month, period.Priority, Product = p == null ? null : p.Product, Demand = p == null ? -1 : p.Demand }; 

    foreach (var a in res) 
      { 
       Console.WriteLine(string.Format("{0} {1} {2}", a.Product, a.Month, a.Demand)); 
      } 

을 그 (당신이 당신의 예에 명시된 바와 같이) 일치 개월 등 위치가없는이없는 제품

+0

@Vitality. 필자는 일치하는 마침표가없는 레코드를 기본값으로 null로 작성해야하기 때문에 왼쪽 결합이 내 경우에는 작동하지 않습니다. – user320587

+0

@ user320587 이것은 OUTER 조인입니다. 그것은 당신에게 필요한 것을 정확하게 줄 것입니다. 기본 -1 값은 이후에 널 (null)로 변환 될 수 있지만, 중요한 것은 누락되었음을 표시하는 것입니다. 쿼리를 실행하여 직접 결과를 확인하고 내가 참조한 설명서를 읽으시기 바랍니다. – Vitaliy

+0

@Vitality. 네, LinqPad를 사용하여 쿼리를 시도했는데 누락 된 기간을 결정할 수있었습니다. 그 후에는 원래 테이블로 많은 항목을 선택하고 누락 된 레코드를 얻을 수 있습니다. 감사합니다 – user320587

관련 문제