Click here to Skip to main content
15,892,575 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i try to perform dynamic linq group by query. the second linq statement should generate same result as first linq statement. can anyone show me why the second linq statement cant work. thx

C#
DataTable dt = new DataTable();
           dt.Columns.Add("ID");
           dt.Columns.Add("Name");
           dt.Columns.Add("ProductName");

           dt.Rows.Add("1", "aa", "TypeA");
           dt.Rows.Add("2", "bb", "TypeA");
           dt.Rows.Add("3", "cc", "TypeB");

           //1st Linq
           var lotSum = dt.AsEnumerable()
                        .GroupBy(x => new { id = x.Field<string>("id"), product = x.Field<string>("ProductName"), }).ToList();

           // Second Linq
           //Why can't work? anything wrong ??
           var gcol = new string[] { "ID", "ProductName" };
           var gtype = dt.Rows[0].GetType();
           var lotSum2 = dt.AsEnumerable()
                         .GroupBy(g => string.Join(",",  gcol.Select(c => gtype.GetProperty(c).GetValue(g, null)))).ToList();
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900