If you want to get groups of entities from an entitycollection in C# you can use Linq:

Assignment class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Rvl.HelperTools.Common.BE
{
    public class Assignment
    {
        public DateTime Startdate { get; set; }
        public DateTime Enddate { get; set; }
        public string Customername { get; set; }
    }
}

Create function

        public void CreateGroupsOfEntitiesFromEntityCollection()
        {
            List<Assignment> sourceAssignments = new List<Assignment>()
            {
                new Assignment() { Startdate = DateTime.Now.AddDays(1), Enddate = DateTime.Now.AddDays(2), Customername = "Microsoft" },
                new Assignment() { Startdate = DateTime.Now, Enddate = DateTime.Now.AddDays(1), Customername = "Microsoft" },
                new Assignment() { Startdate = DateTime.Now.AddDays(1), Enddate = DateTime.Now.AddDays(2), Customername = "IBM" },
                new Assignment() { Startdate = DateTime.Now, Enddate = DateTime.Now.AddDays(1), Customername = "IBM" },
                new Assignment() { Startdate = DateTime.Now.AddDays(1), Enddate = DateTime.Now.AddDays(2), Customername = "Google" },
                new Assignment() { Startdate = DateTime.Now, Enddate = DateTime.Now.AddDays(1), Customername = "Google" }
            };

            var assignmentGroups = from a in sourceAssignments
                                   orderby a.Customername, a.Startdate
                                   group a by a.Customername into g select new { Customername = g.Key, Assignments = g };

            foreach (var g in assignmentGroups)
            {
                Console.WriteLine(string.Format("Customername {0}", g.Customername));
                foreach (var a in g.Assignments)
                {
                    Console.WriteLine(string.Format("Assignment startdate {0}", a.Startdate));
                }
            }
        }

Result

Customername Google

Assignment startdate 30-10-2009 11:17:47

Assignment startdate 31-10-2009 11:17:47

Customername IBM

Assignment startdate 30-10-2009 11:17:47

Assignment startdate 31-10-2009 11:17:47

Customername Microsoft

Assignment startdate 30-10-2009 11:17:47

Assignment startdate 31-10-2009 11:17:47

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.