1

I am trying to convert from datatable to array[] using linq and then join that array in one string using string.join.

Here is the code:

string.Join("','", dt
  .Select("IsCount = '1'")
  .OfType<DataRow>()
  .Select(dr => dr.Field<string>(0))
  .ToArray())

But it gives error like:

Expression cannot contain lambda expressions

9
  • 1
    .ToArray() is redundant in the context, since string.Join accepts IEnumerable<T> Commented Apr 24, 2017 at 12:38
  • The error you see is from the debugger. What is the actual problem? Commented Apr 24, 2017 at 12:39
  • Cannot reproduce the problem. What NET version are you using? Commented Apr 24, 2017 at 12:41
  • Think this could help stackoverflow.com/questions/23470607/… Commented Apr 24, 2017 at 12:44
  • @Tim Schmelter actual error is cannot perform '=' operation on System.Boolean and System.String. Commented Apr 24, 2017 at 12:46

1 Answer 1

0

The reason for the error is that you compare a bool column with the string "1". That doesn't work in DataTable.Select. You can look how the syntax works and what it supports in DataColumn.Expression:

Boolean literals are true and false; they are not quoted in expressions.

So this would work:

string result = string.Join("','", dt
  .Select("IsCount = true")
  .Cast<DataRow>()
  .Select(dr => dr.Field<string>(0))); // no need for ToArray with NET 4 

But instead of the strange and old Select syntax, why don't you use only LINQ?

string result = string.Join("','", dt.AsEnumerable()
  .Where(row => row.Field<bool>("IsCount"))
  .Select(row => row.Field<string>(0))); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.