本文介绍了通过与日期字段周的IEnumerable列表C#的LINQ或Lambda表达式组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个查询到的IEnumerable<对象> 由周组,例如:

 项目(名称,DateStart,ID)

我有的IEnumerable<项目> ,我希望做一个报告,按周分组



有关〔实施例:

 周1 
PROJECT1 2013年8月4日ID1
Project2的2013年9月4日ID2
周2
PROJECT1 16/4/2013 ID3
Project2的18/4/2013 ID5
第3周
PROJECT1 24/4/2013 ID7
Project2的26/4/2013 ID8

请,如果有人能够给我一个手,我真的很感激!我试图做一个lambda表达式,但没有成功。



谢谢!


解决方案

  VAR weekGroups =项目
。选择(p =>新建
{
项目= p,
年= p。 DateStart.Year,
周= CultureInfo.InvariantCulture.Calendar.GetWeekOfYear
(p.DateStart,CalendarWeekRule.FirstFourDayWeek,DayOfWeek.Monday)
})
.GroupBy(X => ;新{x.Year,x.Week})
。选择((G,I)=>新建
{
WeekGroup = G,
WEEKNUM = I + 1 ,
=年g.Key.Year,
CalendarWeek = g.Key.Week
});

的foreach(在weekGroups VAR projGroup)
{
Console.WriteLine(周+ projGroup.WeekNum);
的foreach(在projGroup.WeekGroup VAR PROJ)
Console.WriteLine({0} {1} {2},
proj.Project.Name,
proj.Project .DateStart.ToString(D),
proj.Project.ID);
}


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!

解决方案
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);
}

这篇关于通过与日期字段周的IEnumerable列表C#的LINQ或Lambda表达式组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 10:01