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

c# dynamic-linq linq

Question

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
0
10/22/2013 9:45:52 AM

Popular Answer

you can use reflection like this

foreach (var v in gFieldList)
       {
              MessageBox.Show(key.GetType().GetProperty(v).GetValue(key,null));
...
2
11/6/2013 1:42:18 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow