Linq query - group by column that does not exist in table

Zeeshan Dar 41 Reputation points
2022-01-11T17:48:34.607+00:00

List of columns from Table1

string groupByColumnsJoined = string.Format("new ({0})", String.Join(", ", groupByColumns));  

Using dynamic group by to query Table2

                var query = dataTable2  
                                .AsEnumerable()
                                .AsQueryable()
                                .GroupBy(groupByColumnsJoined, "it")
                                .Select("it.First()");

The groupByColumnsJoined may contain column names that are not part of Table2 (dataTable2). How to handle the Linq query in this scenario?

Community Center Not monitored
Developer technologies C#
{count} votes

1 answer

Sort by: Most helpful
  1. Jack J Jun 25,296 Reputation points
    2022-01-12T03:21:22.76+00:00

    @Zeeshan Dar , you could remove the unused column names in the databale2.

    Here is a code example you could refer to:

    var groupByColumns =new List<string>() {"Name","Age","Id","Address" };

        string groupByColumnsJoined = string.Format("new ({0})", String.Join(", ", groupByColumns));  
    
        var dataTable2 = new DataTable();  
        dataTable2.Columns.Add("Name");  
        dataTable2.Columns.Add("Age");  
        dataTable2.Columns.Add("Id");  
        dataTable2.Rows.Add("test1",22,1001);  
        dataTable2.Rows.Add("test2", 23, 1002);  
        dataTable2.Rows.Add("test3", 24, 1003);  
        List<string> list2 = new List<string>();  
    
        foreach (DataColumn item in dataTable2.Columns)  
        {  
            list2.Add(item.ColumnName);  
        }  
        IEnumerable<string> result = groupByColumns.Intersect(list2);  
        var list1 = (from DataRow dr in dataTable2.Rows  
                     select new  
                     {  
                         Name = dr["Name"].ToString(),  
                         Age = Convert.ToInt32(dr["Age"].ToString()),  
                         Id = Convert.ToInt32(dr["Id"].ToString()),  
                     }).ToList();  
    
        var query = list1.GroupBy(result, "it")  
                            .Select("it");  
    

    If the response is helpful, please click "Accept Answer" and upvote it.

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.