LINQ聚合和分组通过确定正确的数据

本文关键字:数据 LINQ | 更新日期: 2023-09-27 18:27:59

我有一个List<ShipmentInformation>

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。

LINQ聚合和分组通过确定正确的数据

只需保存每个类型合计的最短日期,然后在聚合中将其考虑在内(顺便说一句,在我看来,使用简单的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;

您需要将最小日期添加到匿名类中。使用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;