2012-03-15 5 views
0

내가 가지고 List<ShipmentInformation>LINQ 집계 및 GROUPBY 결정 정확한 데이터

public class ShipmentInformation 
{ 
    public string Type { get; set; } 
    public long StartID { get; set; } 
    public long EndID { get; set; } 
    public DateTime BoxDate { get; set; } 
} 

가장 주가가 어디는 현재 결정이 코드를 가지고 : 그러나

var TypeTotals = shipmentInfo.GroupBy(x => x.Type).Select(x => new { Type = x.Key, Total = x.Sum(y => (y.EndID - y.StartID) + 1) }); 

//Select the one with the largest amount of stock 
var LargestType = TypeTotals.Aggregate((l, r) => l.Total > r.Total ? l : r).Chip; 

합계가 정확히 동일한 경우 TypeTotals의 마지막 항목을 선택하므로 수표를 추가하여 가장 오래된 BoxDate이 사용되도록하고 싶습니다.

따라서 유형 B의 10 개 항목과 유형 B가 10 개 있다고 가정 해 보겠습니다. 유형 B가 선택됩니다.

이제 LargestType을 반환 할 때 해당 유형의 가장 초기 항목을 반환하는지 확인하고 싶습니다. 따라서 A에있는 항목 중 B에있는 항목보다 이전에 BoxDate가 있으면 A를 선택해야합니다.

답변

3

그냥 각 유형의 총의 최소 날짜를 저장 한 다음 (내 의견으로는 청소기 간단한 foreach 루프 것 그런데하는) 당신의 집계에서 고려

var TypeTotals = shipmentInfo.GroupBy(x => x.Type) 
          .Select(x => new 
          { 
           Type = x.Key, 
           Total = x.Sum(y => (y.EndID - y.StartID) + 1), 
           Date = x.Min(z=> z.BoxDate) 
          }); 

var LargestType = TypeTotals.Aggregate((l, r) => 
{ 
if(l.Total > r.Total) 
    return l; 
else if(l.Total == r.Total) 
    return l.Date < r.Date ? l : r; 
else return r; 
}).Chip; 
+0

대단히 감사합니다. – Jon

2
당신이 필요합니다

을 가져 익명 클래스에 최소 날짜를 추가하십시오. 그리고 집계 대신 OrderBy와 First를 사용하십시오.

var TypeTotals = shipmentInfo 
        .GroupBy(x => x.Type) 
        .Select(x => new 
            { 
             Type = x.Key, 
             Total = x.Sum(y => (y.EndID - y.StartID) + 1), 
             MinBoxDate = x.Min(z => z.BoxDate) 
            }); 

//Select the one with the largest amount of stock 
var LargestType = TypeTotals 
         .OrderByDescending(l => l.Total) 
         .ThenBy(l => l.MinBoxDate) 
         .First().Chip;