0
我有一個動態Linq查詢,通過它我試圖訪問分組數據,分組在兩列和1列上使用聚合函數。如何使用IEnumerable的動態鍵/值對訪問動態linq的結果?
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'
的定義我認爲這有助於[通過字符串獲取c#動態屬性的值](http://stackoverflow.com/questions/4939508/get-value-of-c-sharp-dynamic-property-via-string) – Grundy
另外,如果你在編譯時知道字段列表,你可以使用類似T4的東西 – Grundy