Benny Ae
Benny Ae

Reputation: 2016

Linq to SQL select multiple columns

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>

Upvotes: 6

Views: 50613

Answers (3)

AR M
AR M

Reputation: 313

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

Upvotes: 3

Tobias
Tobias

Reputation: 5108

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

Upvotes: 11

Ahsan
Ahsan

Reputation: 2518

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

Upvotes: 4

Related Questions