codemonkeyliketab codemonkeyliketab - 7 months ago 28
Vb.net Question

Return DataRow whose field is the max for specified column

I want to be able to get a datarow from a datarow array where the datarow has the maximum value for a specified column in all of the datarows.

I imagine it would follow suit to this LINQ statement

Dim minRow As DataRow = myDataRows.AsEnumerable.Min(Function(row) row.Field(Of Decimal)("myColumnName"))


However the Max function returns a decimal instead of a datarow. Is there some easy syntax that handles such a query for me?

And before anyone asks, I tag c# since in winforms they can easily be converted between each other using a website.

Answer

If you can use MoreLINQ, this can easily be done using MaxBy():

var maxRow = myDataRows.MaxBy(r => r.Field<Decimal>("myColumnName"));

But using regular Linq:

var minRow = myDataRows.OrderBy(r => r.Field<decimal>("myColumnName")).FirstOrDefault();
var maxRow = myDataRows.OrderBy(r => r.Field<decimal>("myColumnName")).LastOrDefault();