在一个LINQ中按天,时间和ID分组

时间:2015-06-15 18:56:23

标签: c# linq

我有一个Example类元素列表:

public class Example
{
   public long Id { get; set; }
   public string Name { get; set; }
   public DateTime SomeDate { get; set; }
}

现在我想使用 ONE LINQ对其进行分组,以构建以下层次结构:

public class GroupedByDay
{
   public List<GroupedByTime> TimeGroup { get; set; }
}

public class GroupedByTime
{
   public List<GroupedById> IdGroup { get; set; }
}

public class GroupedById
{
    public string Name { get; set; }
}

因此,结果是List<GroupedByDay>类型的列表,Examples在这些天内按天,小时(时间间隔?)分组,最后由ID分组。

任何人都可以帮我吗?

[编辑]
这是我试图按照ID分组的,但我想我应该从另一方开始呢?

var result =
   examples
      .GroupBy(e => e.Id, e => new GroupedById
         {
            Name = e.Name
         });

2 个答案:

答案 0 :(得分:3)

如果您只是想进行分组以进行展示,则不需要课程GroupedByDayGroupedByTimeGroupedById

考虑examplesIEnumerable<Example>

var groupedExamples = from example in examples 
        group example by new { 
                              example.SomeDate.Date, //Day
                              example.SomeDate.Hour, // Hour
                              example.Id // Id
        } into g
        select g;

然后您将IEnumerable<IGrouping<,Example>>拥有所需的分组:

foreach(var g in groupedExample){
    Console.WriteLine(String.Format("Day {0} at hour {1} with id {2}", g.Key.Date, g.Key.Hour, g.Key.Id));

    foreach(var example in g)
        Console.WriteLine(" - " + example.Name);
}

答案 1 :(得分:-3)

我通常会写这些代码

 public static DateTime GetDateByWeekDay(DateTime startDate, int week, Int32 day)
       {

           int Year = Getyear(startDate);
           DateTime jan1 = new DateTime(Year, 1, 1);
           int daysOffset = DayOfWeek.Monday - jan1.DayOfWeek;

           DateTime firstMonday = jan1.AddDays(daysOffset);
           var cal = CultureInfo.CurrentCulture.Calendar;
           int firstWeek = cal.GetWeekOfYear(firstMonday, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);

           var weekNum = week;
           if (firstWeek <= 1)
           {
               weekNum -= 1;}
           var result = firstMonday.AddDays(weekNum * 7);
           return result.AddDays(day);


       }