LINQ:基于最大值对对象列表进行分组和选择

时间:2012-02-29 20:27:54

标签: c# .net linq

我的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"),
    // ...
}

我如何分组myList,以便我只留下具有Maximum TimeStamp的项目?即结果如下:

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

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

提前致谢。

5 个答案:

答案 0 :(得分:8)

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

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

答案 1 :(得分:3)

从组中选择最大值:

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)

答案 2 :(得分:1)

var temp = myItems.Where(x => x.TimeStamp == myItems.Where(y => y.Name == x.Name).Max(z => z.TimeStamp)).Distinct().ToList();

答案 3 :(得分:0)

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)
};

答案 4 :(得分:0)

好的,我通过在类中添加一个空构造函数来改变你的类MyItem以获得一些LINQ便利(希望这不会导致问题):

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();
}

输出符合您的预期结果。