Domanda

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 ?

È stato utile?

Soluzione

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.

Altri suggerimenti

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));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top