LINQ按天分组和格式化

时间:2014-06-05 05:19:16

标签: c# linq

如果我有一个DateTimes列表或一个由Date Parts组成的对象说:

public class CustomDate
{
    public string Month;
    public string Day;
    public DateTime Date;
}

var cusDate = List<CustomDate>();

是否可以接受它并按月分组以获得:

June 2, 9, 12, 20  May 9, 15, 20, 25 etc ...

如何从以下选项中选择日期字段:

var r = dt.OrderBy(a => a.Date).GroupBy(b => b.Month).Select(a => new { a.Key});

编辑:

获得正确格式的最终​​解决方案:

var il = String.Empty;
var groupped = dt.OrderBy(x => x.Date).GroupBy(x => x.Month);
foreach (var item in groupped)
{
   il += String.Format("{0}", item.Key) + " ";
   foreach (var cd in item)
   {
       il += String.Format("{0}", cd.Day) + ", ";
   }
   il = il.Trim().TrimEnd(',') + " | ";
}

2 个答案:

答案 0 :(得分:0)

我相信你只需要循环GroupBy返回的单个项目。

var groupped = cusDate.OrderBy(x => x.Date)
    .GroupBy(x => x.Month);
foreach (var item in groupped)
{
    Console.WriteLine("Key:{0}", item.Key);
    foreach (var cd in item)
    {
        Console.WriteLine("Date:{0}, Day:{1}, Month:{2}", cd.Date, cd.Day, cd.Month);
    }
}

答案 1 :(得分:-1)

让我们试试这个,将解决你的问题

    var query = cusDate.GroupBy(d=> d.Month)
                      .Select(group => 
                            new { Month= group.Key,
                                  CustomDate = group.OrderByAscending(x => x.Day) })
                      .OrderBy(group => group.CustomDate.First().Day);