Linq Dynamic Columns

  • Thread starter Thread starter Stuart Shay
  • Start date Start date
S

Stuart Shay

Hello All

I have the following LINQ Query in which I only want to return a single
column in the results as a String Array is there a way dyamically change in
the column name.

var expr = from usr in usertList
select new UserAdministrationModel
{
UserName = usr.UserName,
Email = usr.Email
};


//Hardcoded Test Value
string columnName = "Email";

System.Collections.Generic.List<string> items = new
System.Collections.Generic.List<string>();
foreach (var model in expr)
{
if(columnName == "UserName")
items.Add(model.UserName);
else if(columnName == "Email")
items.Add(model.Email);
}

return items.ToArray();
 
Stuart,

You can easily use reflection to return just the items you want.
However, I think you are better off just using the Select extension method
and lambda expressions to get the item you want into an array. That's
unless you are using user input (in the form of a string) to determine which
columns to return.

If you are using LINQ to SQL, then you could use the GetCommand method
on the DataContext to return a reader, which makes it easier to get the
columns from the IQueryable implementation (you don't have to do the mapping
from the data to the object, and it will perform better).
 
Back
Top