1

I am getting a datatable from service. I am using linq to calculate of sum new columns. I want all the coumns in datatable originally plus the new columns calculated in linq.

Problem is columns in datatable are not fixed. How would I dynamically add the columns in select clause of linq.

Below is code snippet:

DataTable dt = ds.Tables[0];
var orderCtr =
from o in dt.AsEnumerable()
where o.Field<string>(Constants.GENDER_NAME) != "Unknown"
group o by new
{
                    odr_id = o.Field<int>(Constants.ORDER_ID),
                    //NEED TO ADD COLUMNS DYNAMICALLY HERE. MEANS IF THEY ARE IN DATATABLE.
                }
                    into g
                    select new
                    {
                         //NEED TO ADD COLUMNS DYNAMICALLY HERE. MEANS IF THEY ARE IN DATATABLE.
                        odr_id = g.Key.odr_id,
                        ac_gr_imp = g.Sum(r => r.Field<long>(Constants.GENDER_IMPRESSION)),
                        ac_gr_clk = g.Sum(r => r.Field<long>(Constants.GENDER_CLICK)),
                        Ctr = (double)g.Sum(r => r.Field<long>(Constants.GENDER_IMPRESSION)) / g.Sum(r => r.Field<long>(Constants.GENDER_CLICK)),
                    };
Adel Khayata
  • 2,717
  • 10
  • 28
  • 46
Ajay
  • 473
  • 7
  • 25

1 Answers1

-1

You might be interested in the Dynamic LINQ library. Dynamic LINQ allows you to specify queries or parts of queries by building strings.

Scott Guthrie described it back in 2008 (http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx) and there is also a NuGet package of it in case you use .NET 4 (http://www.nuget.org/packages/System.Linq.Dynamic).

Roy Dictus
  • 32,551
  • 8
  • 60
  • 76