Saturday 4 February 2012

GroupBy multiple columns using Dynamic LINQ

It can be quite useful at times to have the capability to identify duplicate objects based on custom rules (or in my case based on user input). Since this input is not known at design time, I started looking for a Dynamic Linq functionality that would take a collection of objects, a list of columns and dynamically group by the list of columns at runtime.

The closest I came to what I was looking for is a listing on Scott Gu's blog. There's a link in the blog to download the DynamicLibrary.

Now the following function can be authored to utilise the "GroupBy" extension method on the downloaded class to perform the Dlinq operation.

var query = customerData.AsQueryable().GroupBy("new ("Title, FirstName, LastName")", "it", null);
var groupedCustomerData = (from IEnumerable<Customer> groupedData in
query select groupedData.FirstOrDefault()).ToList();

return groupedCustomerData;


The "it" keyword is used as the KeySelector parameter if the requirement is to return the whole customer object in the group. The code above should group the customer data collection by the Title, FirstName and the LastName attributes.

1 comment:

  1. This can also be achieved as where criteria is my input class
    var data6 = LstAll.AsQueryable()
    .GroupBy(@"new (" + Criteria.GroupBy.GroupByColumn + ")", "it")
    .Cast().AsEnumerable().ToList();

    ReplyDelete