如何使用IEnumerable的动态键/值对访问动态linq的结果?

时间:2013-10-22 09:13:46

标签: c# linq dynamic-linq

我有一个动态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'的定义

1 个答案:

答案 0 :(得分:2)

你可以使用像这样的反射

foreach (var v in gFieldList)
       {
              MessageBox.Show(key.GetType().GetProperty(v).GetValue(key,null));
...