views:

129

answers:

2

Is there a good way of requesting only specified columns from the database using LINQ? I want to be able to select only certain columns depending on arbitrary conditions from code.

A: 

Not sure exactly what you mean.

Are you maybe wanting to pull different columns based on a conditional?

Something like this?

if(condition)
{
    table.Select(x => x.ColumnA);
}
else
{
    table.Select(x => x.ColumnB);
}
Andy_Vulhop
+1  A: 

You can create anonymous types for each condition, which contain only the columns you specify.

var anonymousType = from item in itemCollection
   select new {Column1 = item.Column1, Column2 = item.Column2};

var anonymousType2 = from item in itemCollection
   select new {Column2 = item.Column2, Column3 = item.Column3};
Luis
so I have to create an anonymousType for each and every combination of columns that I have for each table?.. wow
seanlinmt
I guess it all depends how complicated your implementation is. Creating anonymous types from a query is the quick solution (the point of LINQ being to make these things easy and maintainable). If you need a more complicated solution, the link you commented seems to do the trick. (+1)
Luis