6

I just want to select 2 columns from a MSSQL DB using LINQ.

The SQL should be

select table.col1,table.col2 from table

I tried

IList<string> myResults =
(
    from data in dbconn.table
    where table.col5 == null
    select new { 
        col1=data.Id.ToString(),
        col2=data.col2
    }
).Take(20).ToList();

but this didn't work.

It says

cannot convert type  list <AnonymousType#1> to Ilist<string>
2
  • 1
    When you say it doesn't work, what do you mean? Is there an exception? Does it return nothing, or something other than you expect? Commented Oct 1, 2013 at 0:28
  • Note: your LINQ query sample/attempt does not seem consistent with your "SQL should be" statement. Perhaps you could clarify your objective as well as the actual issue Commented Oct 1, 2013 at 0:37

3 Answers 3

11

You are basically trying to fill a list of strings with the entries of a list of anonymous types, that won't work.

Have you tried something like this?:

var list = from data in dbconn.table
           where table.col5 == null
           select new { 
            col1=data.Id.ToString(),
            col2=data.col2
           }

Then you can easily use the entries in a loop for example

foreach(var element in list) {
//...
}

Or like a list

list.Take(20).ToList();
Sign up to request clarification or add additional context in comments.

Comments

4

First of all, a list of strings (List<string>) can only have one single string in an element not two (what you are trying to do here) changing the type to var would fix your exception but not sure if that is the solution you want.

var myResults =
(
    from data in dbconn.table
    where table.col5 == null
    select new { 
        col1=data.Id.ToString(),
        col2=data.col2
    }
).Take(20).ToList();

Comments

3

You can select multiple fields using linq Select as shown above in various examples this will return as an Anonymous Type. If you want to avoid this anonymous type here is the simple trick.

var items = myResults.Select(f => new [] { f.Col1, f.Col2 }).SelectMany(item => item).Distinct();

I think this solves the problem

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.