简体   繁体   中英

Groupby using dynamic linq

Can anybody help me get this work?

I have the following code :

dt.Columns.Add("Field1", typeof(String));
dt.Columns.Add("Field2", typeof(String));
dt.Columns.Add("NR", typeof(Double));

dt.Rows.Add("A", "990001", 100);
dt.Rows.Add("A", "990001", 120);
dt.Rows.Add("B", "990001", 200);
dt.Rows.Add("B", "990001", 300);

var fields = new List<string>() { "Field1", "Field2" };

var q = dt.AsEnumerable().AsQueryable()
          .GroupBy("new(" +  qfields + ")", "it")
          .Select("new(Key as Group, Sum(NR) as Tot)");

When I execute this code I get the error:

No property or field 'NR' exists in type 'DataRow'

I need the result as:

A, 990001, 220
B, 990001, 500
var q =
    dt.AsEnumerable()
        .AsQueryable()
        .GroupBy("new(it[\"Field1\"] as Field1,it[\"Field2\"]as Field2)", "it")
        .Select("new(Key as Group, Sum(double(it[\"NR\"])) as Tot)");
foreach (var v in q)
{
    Console.WriteLine(v);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM