Based on comments and the question, you want: for each distinct id, the instance with the maximum dt
.
I would add a help method: MaxBy
which allows a whole object to be selected based on the value of a function1:
public static T MaxBy<T,TValue>(this IEnumerable<T> input, Func<T,TValue> projector)
where TValue : IComparable<TValue> {
T found = default(T);
TValue max = default(TValue);
foreach (T t in input) {
TValue p = projector(t);
if (max.CompareTo(p) > 0) {
found = t;
max = p;
}
}
return found;
}
And then the query becomes:
var q = from p in TestList
group p by p.id into g
select g.MaxBy(w => w.dt);
NB. this implementation of MaxBy
will only work for objects where the value of the member being compared is greater than its type's default value (e.g. for int
: greater than zero). A better implementation of MaxBy
would use the enumerator manually and initialise both found
and max
variables directly from the first element of the input.
1 if you are using The Reactive Extensions (Rx) this is included in the System.Interactive
assembly.