Angel Hernández

Grouping by more than a column in LINQ / Agrupando por más de una columna en LINQ

LINQ is a very powerful feature in .NET, however its syntax can be a bit confusing sometimes for some developers plus having the ability to perform queries in our code it’s not a novelty either, I did some FoxPro in the past and this capability was present already, so using and implementing LINQ it’s not that difficult to me =)  Anyways… Some days ago I had to write and implement some caching mechanism on this SharePoint based solution I’m currently working on which integrates SAP, CRM, WebMethods, AJAX and so on. The issue I had was related to grouping data based on more than one column (which it’s not LINQ’s out-of-the-box functionality), let’s remember that grouping it’s provided by the Queryable class and my working data was based on a DataTable which it’s a totally different class…  so I came with this easy and quick idea to implement, since I’m using LINQ to ADO.NET and DataSets as well as DataTable don’t contain the AsQueryable extension method I had to create a “pseudo” extension method to handle DataRow collections then use a Func delegate which is going to be passed to the IEnumerable<T>.GroupBy extension method, you may be wondering by now, but what does the method targeted by the delegate do? Well… It’s a very simple a short answer, I just create a unique key (used to group my data) based on concatenating the value for the columns I want to group by and voila!  it’s works… It’s not hard or time consuming to implement and it gives me the results that I’m expecting. The images shown below illustrate the code that’s required to accomplish this.

Kind regards,

Angel


LINQ es una característica muy poderosa en .NET, sin embargo su sintaxis puede ser un poco confusa algunas veces para los desarrollares, además la capacidad de realizar consultas en nuestro código tampoco es una novedad, yo desarrollé con FoxPro en el pasado y ésta característica estuvo siempre presente, así que utilizar ó implementar LINQ no es tan difícil para mí =) En fin… Hace unos días atrás tuve que escribir e implementar un mecanismo de caché para ésta solución basada en SharePoint  en la que trabajo actualmente la cual integra SAP, CRM, WebMethods, AJAX y pare usted de contar. El problema que tenía era en relación al agrupamiento de datos basado en más de una columna (Lo cuál no es una funcionalidad por defecto en LINQ), recordemos que el agrupamiento está dado por la clase Queryable y mis datos estaban almacenados en un DataTable los cuales son una clase totalmente distinta, por lo que se me ocurrió ésta idea que resultó ser rápida y fácil de implementar; ya que estoy utilizando LINQ con ADO.NET y DataSets al igual que DataTable no contienen el método de extensión AsQueryable tuve entonces que crear un “pseudo” método de extensión para manipular una colección de DataRow que me permitiera después utilizar un delegado Func que posteriormente es pasado al método de extensión IEnumerable<T>.GroupBy, ustedes se estarán preguntándose ahora, pero qué hace el método apuntado por el delegado?  Bueno… Es una respuesta corta y sencilla, sólo creo una clave única (utilizada para agrupar mis datos) a partir de concatenar el valor de las columnas por la cual quiero agrupar y voila!  Funciona… No es díficil ó toma tiempo para hácerlo y me da los resultados que espero. Las imágenes mostradas a continuación contienen el código que es necesario para conseguir esto.

Saludos cordiales,

Angel

 

image

Image 1 – GetTestData method

image

Image 2 – GroupData method

image

Image 3 – EnumerableDataRowExtension class

image

Image 4 – PerformDataGrouping method

image

Image 5 – It’s so easy to do in FoxPro =)

Leave a Comment

(required) 

(required) 

(optional)

(required)