문제

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