Friday, December 7, 2012

Group by and Sub group in Linq



Created a result set (Using IBATIS.NET Datamapper technology to load object using Stored Procedure method) as on object.

IList<CLASS1> objReport1 = new List<CLASS1>();

IList<CLASS> objReportBase = DataLayer.MethodName(strParam, 1, "N");

if (objReportBase.Count > 0)
{
               objReportNew = (from p in objReportBase
                                group p by new
                                {
                                    p.USERID,
                                    p.DISPLAYUSERID,
                                    p.LASTNAME,
                                    p.FIRSTNAME
                                } into g
                                orderby g.Key.LASTNAME, g.Key.SUITENAME
                                select new CLASS1
                                {
                                    USERID = g.Key.USERID,
                                    DISPLAYUSERID = g.Key.DISPLAYUSERID,
                                    LASTNAME = g.Key.LASTNAME,
                                    FIRSTNAME = g.Key.FIRSTNAME,
                                   
                                    subPVCs = g.Select(l => new
                                                {
                                                    l.COURSENAME,
                                                    l.MASTEREDDATE,
                                                    l.ASSIGNEDDATE,
                                                    l.MASTEREDSCORE,
                                                }
                                             ).Distinct()
                                }).ToList<CLASS1>();

                objReportBase = null;
}
           
public class BASECLASS
{
        public virtual int USERID { get; set; }
        public virtual string DISPLAYUSERID { get; set; }
        public virtual string LASTNAME { get; set; }
        public virtual string FIRSTNAME { get; set; }
        public virtual string COURSENAME { gets; set; }
        public virtual string MASTEREDDATE { get; set; }
        public virtual string ASSIGNEDDATE { get; set; }
        public virtual string MASTEREDSCORE { get; set; }
}
public class CLASS1
{
        public virtual int USERID { get; set; }
        public virtual string DISPLAYUSERID { get; set; }
        public virtual string LASTNAME { get; set; }
        public virtual string FIRSTNAME { get; set; }

        public virtual IEnumerable subPVCs { get; set; }

}

public class subPVC
{
        public virtual int USERID { get; set; }
        public virtual string COURSENAME { gets; set; }
        public virtual string MASTEREDDATE { get; set; }
        public virtual string ASSIGNEDDATE { get; set; }
        public virtual string MASTEREDSCORE { get; set; }
}