Tom Tom - 11 months ago 29
C# Question

LINQ: How to group anonymous type

I need to fill News object properties and collections . but i don't know what is the correct way to fill them by grouping the result.

For example how to fill properties CategoryId, CategoryName and CommentId , CommentBody

My code looks like this:

var q = (
from news in db.News
from categories in news.Categories
from comments in news.Comments
where news.NewsId == 1
select new { news.NewsId, news.NewsTitle , categories.CategoryId,categories.CategoryName , comments.CommentId, comments.CommentBody }

News ne = new News()
NewsTitle = q.Select(w => w.NewsTitle).FirstOrDefault(),
Categories = q.GroupBy(jj => jj.CategoryName).Select(vv => new Category { CategoryId, CategoryName }).ToList(),
Comments = q.GroupBy(ww => ww.CommentBody).Select(b => new Comment { CommentId , CommentBody }).ToList()

Answer Source

The result of GroupBy is IEnumerable<IGrouping<TKey, TItem>>. This is a loopable set of groups, where each group has a Key and is itself a loopable set of source items.

Categories = q
  .GroupBy(jj => jj.CategoryName)
  .Select(g => new Category
    CategoryId = g.First().CategoryId,
    CategoryName = g.Key

Note: it is safe to call First on a group, as each group always has at least one member.