2012-03-15 58 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

所以我們可以說我有10個A型項目和10個B型項目,此刻會選擇B型。

我想現在確保當我返回LargestType時,它返回該類型的最早的項目。因此,如果A中的任何項目的BoxDate早於B中的任何項目,則應選擇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 2012-03-15 15:46:39

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;