Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: Grouping By and Selecting from a List of objects based on max value

Tags:

c#

.net

linq

I have the MyItem class with 3 properties as below:

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

    // ...
}

also I have a list of MyItem as below:

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

how can I GROUP BY myList so that I am ONLY left with the items that have Maximum TimeStamp? ie the result below:

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

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

Thanks in advance.

like image 351
MaYaN Avatar asked Feb 29 '12 20:02

MaYaN


2 Answers

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

This will select your results in the fastest time possible (at least that I can figure) without creating new objects and iterating over the collection the least amount of times.

like image 108
Christopher Currens Avatar answered Sep 23 '22 20:09

Christopher Currens


Select the Max from the Group:

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)
like image 36
Joe Avatar answered Sep 21 '22 20:09

Joe