How can I access the result of dynamic linq with dynamic key/value pairs of IEnumerable?

点点圈 提交于 2019-12-11 20:15:20

问题


I have a Dynamic Linq query, through which am trying to access grouped data, grouped on two columns, and 1 columns on which aggregation function is used.

 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)");

To access the data from the dQueryResult am using the following code.

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());


                }

The problem is

var gFieldList = new List<string>() { "Supplier", "Country" };
var sFieldList = new List<string>() { "Sales"};

keeps on changing. They both need to be dynamic, which will not allow me to access the values dynamically from the above mentioned code since for now it's been coded as key.Supplier, key.Country and group.Sales .

How can I make the iteration of the result of the dynamic query as dynamic?

I tried using

    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);
           }

  }

But it's throwing an exception stating 'DynamicClass1' does not contain a definition for 'v'


回答1:


you can use reflection like this

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


来源:https://stackoverflow.com/questions/19513663/how-can-i-access-the-result-of-dynamic-linq-with-dynamic-key-value-pairs-of-ienu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!