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
2009-07-02 02:30:36
+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
2009-07-02 02:45:23
so I have to create an anonymousType for each and every combination of columns that I have for each table?.. wow
seanlinmt
2009-07-02 03:46:38
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
2009-07-02 12:52:26