1

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.

2
  • That code shouldn't compile - tableID is being declared twice. Commented Apr 6, 2011 at 13:21
  • @RQDQ, Correct - I changed that for the purposes of this question to make it clear in context. Commented Apr 6, 2011 at 13:24

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0
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(); 

Comments

0
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.