Hierarchical Data Categorization using LINQ to Objects in n-tier applications
I will try to illustrate this with an example. I have two business entities Category and SubCategory.
public class Category
{
public int Id {get;set;}
public List<SubCategory> SC {get;set;} //SubCategory is the child object of category
}
public class SubCategory
{
public int Id {get;set;}
public string Name {get;set;}
}
Output from the SP in my Data Access Layer is combination of the above entities.
A sample output from the SP:
CategoryID | SubCategoryID | SubCategoryName |
1 | 1 | “SC1” |
1 | 2 | “SC2” |
1 | 3 | “SC3” |
1 | 4 | “SC4” |
2 | 1 | “SC5” |
2 | 2 | “SC6” |
3 | 1 | “SC7” |
4 | 1 | “SC8” |
Let me assume the result is stored in an entity which maps the output. Let me call this RecordCategory
public class RecordCategory
{
public int Id {get;set;}
public int SId {get;set;}
public string SName {get;set;}
}
The job now is to convert the rows of records into a hierarchial data struture correspoding to Category-SubCategory entities i.e. every CategoryID should coresspond to s single Catehory object with a list of SubCategory objects having the same CategoryID.
Here is how this is done:
List<RecordCategory> rc = new List<RecordCategory>();
//rc = Retrieve data from SP
//Group the records retrieved form the SP on their
//Category Id using the group by query operattor
IEnumerable<IGrouping<int,RecordCategory>> cat = from p in rc
group p by p.Id;
The data will be grouped hierarchially.But the business layer expects a list of Catgeory objects along with SubCategory data.
List<Category> cat1 = (from c in cat
select new Category {Id = c.Key,Name = c.First().Name, SC =
(
from d in c
where d.Id == c.Key
select new SubCategory{Id = d.SId,Name=d.SName}
).ToList()
}).ToList();//Return the cat1 object to BAL
All we are doing here is running a nested query to group all the SubCategory object inside the Category object.
We could have achieved the same result without using LINQ – but then we had to resort to endless for loops and conditions.This is how elegant our code can get using LINQ!!.
