Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Linq or Lambda expression Group by Week IEnumerable list with date field

Tags:

c#

lambda

linq

I am trying to do a query to an IEnumerable<Object> to group by week, for example:

Project(Name, DateStart,ID)

I have IEnumerable<Project> and I want to do a report, grouping by week.

For exmaple:

Week 1
 Project1  8/4/2013 ID1
 Project2  9/4/2013 ID2
Week 2
 Project1  16/4/2013 ID3
 Project2  18/4/2013 ID5
Week 3
 Project1  24/4/2013 ID7
 Project2  26/4/2013 ID8

Please if someone can give me a hand I really appreciate it! I was trying to do a lambda expression but without success.

Thanks!

like image 727
user2112420 Avatar asked Dec 07 '22 08:12

user2112420


1 Answers

var weekGroups = projects
    .Select(p => new 
    { 
        Project = p, 
        Year = p.DateStart.Year, 
        Week =  CultureInfo.InvariantCulture.Calendar.GetWeekOfYear
                      (p.DateStart, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday)
    })
    .GroupBy(x => new { x.Year, x.Week })
    .Select((g, i) => new 
    { 
        WeekGroup = g, 
        WeekNum = i + 1,
        Year = g.Key.Year,
        CalendarWeek = g.Key.Week
    });

foreach (var projGroup in weekGroups)
{
    Console.WriteLine("Week " + projGroup.WeekNum);
    foreach(var proj in projGroup.WeekGroup)
        Console.WriteLine("{0} {1} {2}", 
            proj.Project.Name, 
            proj.Project.DateStart.ToString("d"), 
            proj.Project.ID);
}
like image 140
Tim Schmelter Avatar answered Jan 06 '23 06:01

Tim Schmelter