LINQ:根据最大值分组和从对象列表中选择

本文关键字:对象 列表 选择 最大值 LINQ | 更新日期: 2023-09-27 18:26:07

我有一个MyItem类,它有3个属性,如下所示:

class MyItem
{
    private string _name;
    private int _value
    private DateTime _TimeStamp;
    public MyItem(string name, int value, string timeStamp)
    {
        this._name = name;
        this._value = value;
        this._timeStamp = DateTime.Parse(timeStamp);
    }
    public string Name
    { get {return this_name; } }
    public int Value
    { get {return this._value; } }
    public DateTime TimeStamp
    { get {return this._timeStamp; } }
    // ...
}

我还有一个MyItem的列表如下:

var myItems = new List<MyItem>() {
    new MyItem("A", 123, "23/02/2012"),
    new MyItem("A", 323, "22/02/2012"),
    new MyItem("B", 432, "23/02/2012"),
    new MyItem("B", 356, "22/02/2012"),
    // ...
}

如何按我的列表分组,以便只剩下具有最大时间戳的项目?即以下结果:

"A"  123  23/02/2012<br>
"B"  432  23/02/2012<br>

提前谢谢。

LINQ:根据最大值分组和从对象列表中选择

myItems.GroupBy(item => item.Name)
       .Select(grp => grp.Aggregate((max, cur) => 
                            (max == null || cur.Date > max.Date) ? cur : max))

这将在尽可能快的时间内(至少我可以想象)选择结果,而无需创建新对象并在集合上迭代最少的次数。

从组中选择最大值:

from item in MyItems
group item by item.Name into grouped
let maxTimeStamp = grouped.Max(i => i.TimeStamp)
select grouped.First(i => i.TimeStamp == maxTimeStamp)
var temp = myItems.Where(x => x.TimeStamp == myItems.Where(y => y.Name == x.Name).Max(z => z.TimeStamp)).Distinct().ToList();
var tmp = select i from myItems
group i by i.Name into g
select new MyItem
{
    g.Name,
    Value = g.OrderByDescending(x => x.Timestamp).First().Value,
    Timestamp = g.Max(x => x.Timestamp)
};

好的,为了LINQ的方便(希望这不会引起问题),我更改了您的类MyItem,在该类中添加了一个空白构造函数:

public MyItem() { }

在一个示例控制台程序中,此代码将起作用:

static void Main(string[] args)
{
    var myItems = new List<MyItem>() 
    {
        new MyItem("A", 123, "23/02/2012"),
        new MyItem("A", 323, "22/02/2012"),
        new MyItem("B", 432, "23/02/2012"),
        new MyItem("B", 356, "22/02/2012")
        // ...
    };
    var grouped = from m in myItems
                  group m by m.Name into g
                  let maxTimestamp = g.Max(t => t.TimeStamp)
                  select new MyItem
                  {
                      Name = g.Key,
                      Value = g.First(f => f.TimeStamp == maxTimestamp).Value,
                      TimeStamp = maxTimestamp
                  };
     foreach (var gItem in grouped)
     {
        Console.WriteLine(gItem.Name + ", " + gItem.Value + ", " + gItem.TimeStamp);
     }
     Console.ReadLine();
}

输出符合您的预期结果。