0

I am currently trying to find the value of a column by comparing the value of another column with a reference number.

Let me explain:

I have a DataTable with 2 columns.

ID    DATA
1     120
2     200
3     -60
4     478

I want to find the ID of the DATA closest from 0.

In this case the correct value will be -60 and the ID 3

I actually do that

int closestId = dtQueryLambda.AsEnumerable().Where(x => x.Field<double> ("DATA") > 0 || 
                                                        x.Field<double>("DATA") < 0) 
    .Select(x => x.Field<Int32>("ID"))
    .First();

Can someone help me?

2
  • What about getting the absolute values and then getting the min? Jul 21, 2016 at 11:08
  • Because i'll in the next step, find in an other DataTable find the index of the data where the target number will be the data of the previous result
    – John R
    Jul 21, 2016 at 11:12

2 Answers 2

1

You can use Aggregate method like this:

double baseValue = 0; // or something else
int closestId = dtQueryLambda.AsEnumerable()
    .Select(dr => new
    {
        Id = dr.Field<int>("ID"),
        Diff = Math.Abs(dr.Field<double>("DATA") - baseValue)
    })
    .Aggregate((a, b) => b.Diff < a.Diff ? b : a).Id;

The above is an efficient standard LINQ To Objects approach. With MoreLINQ it's even simpler:

int closestId = dtQueryLambda.AsEnumerable()
    .MinBy(dr => Math.Abs(dr.Field<double>("DATA") - baseValue))
    .Field<int>("ID");
2
  • The second solution is the best i think, but i can't use MinBy function on a EnumerableRowCollection<DataRow>
    – John R
    Jul 21, 2016 at 12:50
  • Why not? It's implementing IEnumerable<DataRow>, so any extension method should work.
    – Ivan Stoev
    Jul 21, 2016 at 12:59
0

Sort by the absolute value and then select the first

var closestId = dtQueryLambda.AsEnumerable()
    .OrderBy(x => Math.Abs(x.Field<double>("DATA")))
    .Select(x => x.Field<Int32>("ID"))
    .First();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.