Darren Young
Darren Young

Reputation: 11090

c# LINQ Query

I have the following code:

var tableID = from data in studyData.Tables["MX_MD_TABLE"].AsEnumerable()
              where data.Field<string>("table_name").ToLower() == "mbddx_study_set"
              select data.Field<long>("ID").ToString();

string tableID = tableID.ElementAt(0).ToString();

It works as expected and the tableID is what I want. Is there a way for the LINQ query to actually return and store the returned string in as it's value, rather than having to create another object to hold it? I know that this query and a few others I will be doing, will only return the single string.

Thanks.

Upvotes: 1

Views: 104

Answers (3)

topspin
topspin

Reputation: 401

tbls.AsEnumerable().Single(o => o.Field<string>("table_name") == "value").Field<long>("ID").ToString();

Although I question your use of LINQ on a datatable to return a scalar value.

Edit:

LINQ is great and useful and very powerful, but also very expensive. DataTables have their own built-in way to search for data and return results.

See http://msdn.microsoft.com/en-us/library/y06xa2h1(v=VS.100).aspx on MSDN for an example.

Upvotes: 0

Grant Thomas
Grant Thomas

Reputation: 45083

This might be what you want (note the use of FirstOrDefault):

var tableID = (from data in studyData.Tables["MX_MD_TABLE"].AsEnumerable()
          where data.Field<string>("table_name").ToLower() == "mbddx_study_set"
          select data.Field<long>("ID").ToString()).FirstOrDefault();

This will select the first element found in the table that falls within the desired criteria, as opposed to returning a collection; the ID's of elements ought to be unique anyway so you should only ever be looking for a single one, I'd suspect.

Note that it also returns the value as it's expected type as defined by Field<long>, so at this point you just need to call ToString on tableID after checking it returned something - but don't append it to the FirstOrDefault call as that could return null.

Upvotes: 4

Bala R
Bala R

Reputation: 108957

string tableID  = (from data in studyData.Tables["MX_MD_TABLE"].AsEnumerable()
              where data.Field<string>("table_name").ToLower() == "mbddx_study_set"
              select data.Field<long>("ID").ToString()).ElementAt(0).ToString();

Upvotes: 0

Related Questions