I have a DataRow[] consisting of 3 columns I want to sort the collection based on a columns value closest to some given value. i.e. Abs(column - given_value). Can somebody please give me some idea how I can accomplish that ?

有帮助吗?

解决方案

You could try this:

var results = collection.OrderBy( 
     row => Math.Abs(Convert.ToInt32(row["ColumnName"]) - given_value));

Or Convert.ToDouble, i don't know the type you are using.

Note: Is the column allows null, you should check it for DBNULL first before Converting.

其他提示

You can use Linq and Math.Abs

IEnumerable<DataRow> orderedRows = rows
    .OrderBy(r => Math.Abs(r.Field<int>("column") - given_value));

If you want to create a new array: rows = orderedRows.ToArray();

Replace r.Field<int> with the actual type. If it's just a string you need to convert it first:

IEnumerable<DataRow> orderedRows = rows
    .OrderBy(r => Math.Abs(int.Parse(r.Field<string>("column")) - given_value));
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top