Converting the output of a Linq query into a Dictionary is as simple as this:

var categories = (from cat in context.CATEGORIES
select new
{
Id = cat.Id,
Tag = cat.Tag,
Description = cat.Description
}).ToDictionary(x => x.Id,x => x);

But at times our query will return repeated elements. For example lets imagine that I am interested in recovering a list of articles with their associated categories.

My initial query output may look like this:

ArticleId01, Category_Sports, … more data
ArticleId01, Category_Shopping, … more data
ArticleId01, Category_Christmas, … more data
ArticleId02, Category_News, … more data

What I like to do here is transform the above data in a dictionary where the article ID acts as the Dictionary Key, and as a Value I would like to have a list of all the categories that apply to the given article. This can be achieved with the following code:

var q = (from article in context.SP_GET_ARTICLES()
select new
{
Key = article.ArticleID,
CategoryId = article.CategoryID
}).GroupBy(x => x.Key).ToDictionary(x => x.Key, x => x.ToList());

Advertisements