In a dynamic linq query, how do you refer to a field?

c# dynamic-linq

Question

I have a query that needs to be dynamic, I think most of my syntax is right but I do not know how to give it the name of the column I want to group by. I have tried a few different approaches and I always get an error - "No property or field 'name' exists in type 'datarow'

IQueryable<Result> aggregate1 = 
      query1Data.Tables[0].AsEnumerable().AsQueryable()
                .GroupBy("name", "it")
                .Select<Result>("new(Key as Group, Sum(value)as Total)");

I assume I have to use something like Field<string>("name") but I cant figure it out. I have seen the problem on a few forums but no one seems to have a clear answer how to get around the problem.

1
0
8/12/2010 9:31:53 AM

Popular Answer

I'm not sure I understand exactly what you want, but here is a little snippet of code you may use as inspiration:

var dataTable = new DataTable();
dataTable.Columns.Add("Name", typeof(String));
dataTable.Columns.Add("Value", typeof(Int32));
dataTable.Rows.Add("A", 1);
dataTable.Rows.Add("A", 2);
dataTable.Rows.Add("B", 3);
dataTable.Rows.Add("B", 4);

var aggregate = dataTable.AsEnumerable()
  .GroupBy(row => row.Field<String>("Name"), row => dataRow.Field<Int32>("Value"))
  .Select(group => new { Name = group.Key, Total = group.Sum() });

foreach (var row in aggregate)
  Console.WriteLine(row.Name + " = " + row.Total);
0
8/12/2010 9:55:32 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow