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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With