Sunday, August 11, 2013

Group By multiple Columns in DataTable in C# using LINQ

We might came across few scenarios where combination of columns makes Primary key in the DataTable. In such cases we may need to group by multiple columns in the DataTable and create unique records in the table. Using Linq we can implement the above scenario,

                    var qryLatestInterview = from rows in dtPositionInterviews.AsEnumerable()
                                             orderby rows["Created"] descending
                                             group rows by new { PositionID = rows["PositionID"], CandidateID = rows["CandidateID"] } into grp
                                             select grp.First();

                    dtPositionInterviews = qryLatestInterview.CopyToDataTable();



In the above example, combination of CandidateID and PositionID makes the record unique. So we can group the DataTable by CandidateID and PositionID and can get the Unique set.
Related Posts Plugin for WordPress, Blogger...