0

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'

  • i think this help [Get value of c# dynamic property via string](http://stackoverflow.com/questions/4939508/get-value-of-c-sharp-dynamic-property-via-string) – Grundy Oct 24 '13 at 11:18
  • Also if you know field list in compile time you can use something like T4 – Grundy Oct 24 '13 at 11:21

1 Answers1

2

you can use reflection like this

foreach (var v in gFieldList)
       {
              MessageBox.Show(key.GetType().GetProperty(v).GetValue(key,null));
...
Grundy
  • 13,356
  • 3
  • 35
  • 55