我有一个动态 Linq 查询,我试图通过它访问分组数据,分组在两列和 1 列上,其中使用了聚合函数。
var gFieldList = new List<string>() { "Supplier", "Country" };
var sFieldList = new List<string>() { "Sales"};
var gField = string.Join(", ", gFieldList.Select(x => "it[\"" + x + "\"] as " + x));
var sField = string.Join(", ", sFieldList.Select(y => "Sum(Convert.ToDouble(it[\""+y+"\"])) as "+y));
var dQueryResult = dataTable
.AsEnumerable()
.AsQueryable()
.GroupBy("new("+gField+")", "it")
.Select("new("+sField+",it.Key as Key, it as Data)");
要从 dQueryResult 访问数据,请使用以下代码。
var groupedData = (from dynamic dat in dQueryResult select dat).ToList();
foreach (var group in groupedData)
{
var key = group.Key;
var sum = group.Sales;
MessageBox.Show("Supplier : " + key.Supplier + "Country : " + key.Country + " SALES : "+Sale.ToString());
}
问题是
var gFieldList = new List<string>() { "Supplier", "Country" };
var sFieldList = new List<string>() { "Sales"};
不断变化。它们都需要是动态的,这将不允许我从上述代码中动态访问值,因为现在它被编码为 key.Supplier、key.Country 和 group.Sales。
如何使动态查询结果的迭代成为动态的?
我尝试使用
var groupedData = (from dynamic dat in dQueryResult select dat).ToList();
foreach (var group in groupedData)
{
var key = group.Key;
var sum = group.Sales;
foreach (var v in gFieldList)
{
MessageBox.Show(key.v);
}
}
但它抛出了一个异常,指出“DynamicClass1”不包含“v”的定义