问题描述:

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.

网友答案:

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();
网友答案:

A little late but I want to share it anyway ;), you can do it in O(n) instead of O(n*log n) (which is the order for OrderBy extension method) if you use Aggregate extension method:

var minRow =myDataRows.Aggregate(myDataRows[0],(seed,next)=>next.Field<decimal>("myColumnName").Field<decimal>("myColumnName")?next:seed);

Check if your myDataRows array have at least one row

相关阅读:
Top