开发者

How to refer to a field in a dynamic linq query?

开发者 https://www.devze.com 2023-01-11 19:20 出处:网络
I have a query that needs to be dynamic, I think most of my syntax is right but I开发者_C百科 do not know how to give it the name of the column I want to group by. I have tried a few different approac

I have a query that needs to be dynamic, I think most of my syntax is right but I开发者_C百科 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.


Is this what you were trying to do?

var aggregate1 =
        query1Data.Tables[0].AsEnumerable().AsQueryable()
            .GroupBy(row => row.Field<string>("name"), row => row.Field<int>("it"))
            .Select(g => new { Group = g.Key, Total = g.Sum() });


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号