M.Efe Ozer’s Weblog

April 9, 2009

Linq and Group By Multiple Columns

Filed under: .Net, C#, Notes to Myself — Tags: , — Mehmet Efe Ozer @ 2:08 pm

It is typical master detail group by query.

We have data as List<T> which it contains master and detail columns (“SentData” in query).

Our master and detail classes:

public class Master
    {
        public string MasterID { get; set; }
        public string MasterDisplayValue{ get; set; }
        public List<Detail> Details { get; set; }
    }

public class Detail
    {
        public string Detail1 { get; set; }
        public string Detail2 { get; set; }
        public string Detail3 { get; set; }
    }

We define columns for grouping with anonymous type;

var result = SentData.GroupBy(g=>
                new {OwnerID=g.AlbumOwner,OwnerDisplay=g.AlbumOwnerDisplayName })
                .Select(resultgroup =>
                    new Master
                               {
                                   MasterID = resultgroup.Key.OwnerID
                                   ,MasterDisplayValue = resultgroup.Key.OwnerDisplay
                                   ,Details = (resultgroup.Select(d => new Detail
                                   {
                                        Detail1 = d.Caption
                                       ,Detail2 = d.Description
                                       ,Detail3 = d.Count.ToString()
                                   }).ToList())
                               }).ToList();

No Comments Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.