-1

I need to dynamically generate a query to access certain columns from a datatable.

 string cols="row[Id],row[UserId], row[Code]";
 var result= (from DataRow row in dt.Rows
         select cols);

but this only returns "row[Id],row[UserId], row[Code]". How can I access the values in those columns?

Madonna10
  • 33
  • 8
  • 2
    Possible duplicate of [Dynamically generate LINQ queries](http://stackoverflow.com/questions/9505189/dynamically-generate-linq-queries) – user3114639 May 02 '16 at 10:36
  • 1
    Why would this have to be "dynamic"? – Biesi May 02 '16 at 10:44
  • @BiesiGrr I get the list of columns to select only at run time.. – Madonna10 May 02 '16 at 10:52
  • @Madonna10 `DataRow` can get the value of the column by it's name. This should just work fine for what you're trying to do? Just use a simple loop – Biesi May 02 '16 at 10:58
  • You can try running c# code at runtime http://stackoverflow.com/questions/4181668/execute-c-sharp-code-at-runtime-from-code-file (Or much easier: If you are just want to select dynamic columns, just select them all `*` and from your code use whatever columns you want and ignore the rest) –  May 02 '16 at 11:00
  • Why not putting it in a dictionary? `Dictionary` the key is the column name and the value is the value of the column? – Sebastian Siemens May 02 '16 at 11:39

2 Answers2

0

I doubt this problem can be solved elegantly with a linq-based solution. It can be solved pretty easily using a loop and by accessing the column of the DataRow using the Item property.

public IEnumerable<object[]> GetValues(IList<string> columns, DataTable dt) {
  foreach (var row in dt.Rows) {
    var rowResult = new object[columns.Count];
    for (var col = 0; col < columns.Count; col++) {
      rowResult[col] = row.Item[columns[col]];
    }
    yield return rowResult;
  }
}
Andreas
  • 6,447
  • 2
  • 34
  • 46
0

Why not putting it in a dictionary? Dictionary<string, object> the key is the column name and the value is the value of the column.

        string[] cols = new string[] { "Id", "UserId", "Code" };
        var result = (from DataRow row in dt.Rows
                      select cols.ToDictionary(c => c, c => row[c]));
Sebastian Siemens
  • 2,302
  • 1
  • 17
  • 24