0

I have a list of column names. I want to iterate fetched data using list of column names, so what generic type should I use to convert fetched data into?

Edit:

List<string> columns = new List<string>();
columns.Add("column1");
columns.Add("column2");
columns.Add("column3");

string joinColumns = string.Join(",", columns);
string sql = "select "+joinColumns+" from Table";

It will fetched only selected columns, So how would I do same functionality using entity framework instead of using sql query?

Thanks in advance. Help is appreciated.

Solution- This is not possible in link so alternative to this, I converted List to DataTable using extension method described in the link - https://stackoverflow.com/a/5805044/1416033

List<string> columns = new List<string>();
columns.Add("column1");
columns.Add("column2");
columns.Add("column3");

List<Accounts> accountList = GetAccountList();
DataTable dt = accountList.ToDataTable<Accounts>();
foreach (DataRow dr in dt.Rows)
{
   foreach (string column in columns)
   {
      val = dr[column].ToString();
   }
}
Community
  • 1
  • 1
Hiral
  • 153
  • 5
  • 18
  • context.Table.Where should return an IQueryable of the Table model classes. – Garrison Neely Sep 19 '13 at 16:28
  • @GarrisonNeely I know it will return IQueryable but if I want to access that fetched data by column name then into what generic type should I convert my fetched data? – Hiral Sep 19 '13 at 16:30
  • If you append a .ToList() at the end, it will return a List that will persist outside of the method's scope. Table should have all the columns you have in the database, by default.
    – Garrison Neely Sep 19 '13 at 16:32
  • @GarrisonNeely If I get data into .ToList(), that list contains one of the column XYZ, then how come I access that 'XYZ' column value directly? – Hiral Sep 19 '13 at 16:34
  • you can use an anonymous type http://msdn.microsoft.com/en-us/library/vstudio/bb397696.aspx – qujck Sep 19 '13 at 16:38

1 Answers1

0

What you describe isn't going to work with native LINQ functionality. There is a library though, that should help you. Check out Dynamic LINQ: http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

Garrison Neely
  • 3,238
  • 3
  • 27
  • 39
  • I didn't know that it is not possible in LINQ. So thanks for the info. I didn't use Dynamic LINQ instead I use extension method, I have updated my question with solution. – Hiral Sep 19 '13 at 20:45