Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 350
Benny Ae Avatar asked Oct 01 '13 00:10

Benny Ae


2 Answers

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();
like image 160
Tobias Avatar answered Nov 14 '22 21:11

Tobias


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();
like image 37
Ahsan Avatar answered Nov 14 '22 21:11

Ahsan