Premanshu
Premanshu

Reputation: 626

Datatable linq select query

I m trying to select a column's value from a datatable based on conditions.

var results = from DataRow myRow in dtCallBack.AsEnumerable()
              where myRow.Field<DateTime>(1) == startDateTime
                 && myRow.Field<int>(0) == callBackID
              select myRow.Field<int>(3);

My datatable contains 4 columns ID,Date1,Date2,IntVal

I want to convert the variable results to int. (I want to return the column 4 IntVal)

Upvotes: 0

Views: 2920

Answers (2)

Thanh Nguyen
Thanh Nguyen

Reputation: 1056

var results = (from DataRow myRow in dtCallBack.AsEnumerable
              where myRow.Field<DateTime>(1) == startDateTime 
              && myRow.Field<int>(0) == callBackID
              select myRow.Field<int>(3)).SingleOrDefault();

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500065

Well you've currently got an IEnumerable<int> by the looks of it. So which of those results do you want? What do you want to happen if there aren't any results?

If you're confident there's only a single result, you can use:

var result = results.Single();

If you want the first result or 0 if there aren't any, you could use

var result = results.FirstOrDefault();

If you want the first result and an exception if there aren't any, you could use

var result = results.First();

Basically there are lots of options, and you'll need to clarify your requirements before we can really give you a more concrete answer.

Upvotes: 1

Related Questions