0

In the bellow Linq Statement, i have used GroupBY Clause for e.g.

.GroupBy(i => new{ID = i.Field<decimal>("ID"),COL1 = i.Field<string>("COL1"),COL2 = i.Field<string>("COL2")})

Help me in making GroupBy clause dynamic, as column names COL1, COL2 will be retrieved from datatable and column names might change/ increase/ decrease, but column ID would be present. Hence suggest me how we can make groupby clause dynamic in linq statement.

Linq Example

    DataTable dt2 = new DataTable("Order");  
    DataColumn dc2 = dt2.Columns.Add("ID", typeof(decimal));  
    dt2.Columns.Add("AMT", typeof(decimal));  
    dt2.Columns.Add("PERCENTAGE", typeof(decimal));  
    dt2.Columns.Add("COL1", typeof(String));  
    dt2.Columns.Add("COL2", typeof(String));

    dt2.Rows.Add(6, 200,100,"xxx","yyy");  
    dt2.Rows.Add(8, 400, 100,"qqq","fff");  
    dt2.Rows.Add(1, 300, 100,"eee","aaa");  
    dt2.Rows.Add(1, 200, 100,"eee","aaa");  
    dt2.Rows.Add(10,400,100,"sss","vvv"); 

    var duplicates = dt2.AsEnumerable()   
                    .GroupBy(i => new{ID = i.Field<decimal>("ID"),COL1 = i.Field<string>("COL1"),COL2 = i.Field<string>("COL2")})
                    .Where(g => g.Count() > 1)
                    .Select(g =>
                      {
                        var row = dt2.NewRow();
                         row["ID"] = g.Key.ID;
                         row["COL1"] = g.Key.COL1;
                         row["COL2"] = g.Key.COL2;
                         row["AMT"] = g.Sum(r => r.Field<decimal>("AMT"));
                         row["PERCENTAGE"] = g.Sum(r => r.Field<decimal>("PERCENTAGE"));
                         return row;
                       }).CopyToDataTable();

                        foreach(DataRow row in duplicates.Rows)
                        {
                            Console.WriteLine(row["ID"].ToString() + " " + row["COL1"].ToString() + " " + row["COL2"].ToString() + " " + row["AMT"].ToString() + " " + row["PERCENTAGE"].ToString()) ;

                        }

Thanks.

  • Well, [here's just one way](https://stackoverflow.com/q/55491169/861716) to do it and there are more posts on this. – Gert Arnold Jul 06 '19 at 18:44

1 Answers1

0

I can suggest 2 approaches to make your GroupBy dynamic:

  1. Use string variable in your query:
var column1 = "COL1"; // user input
var column2 = "COL2"; // user input

// the querying ...

.GroupBy(i => new
            {
            ID = i.Field<decimal>("ID")
            , COL1 = i.Field<string>(column1)
            , COL2 = i.Field<string>(column2)
            }
         )
  1. Use System.Dynamic.Linq package for dynamic querying

Which makes it more complex! Here is an example of it here.


I prefer the first approach because it's easy and not require extra efforts and libraries.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Ali Bahrami
  • 5,935
  • 3
  • 34
  • 53