开发者

Generate unique groups for year/month/day/hour in a "yyyy.mm.dd.hh" string in linq

开发者 https://www.devze.com 2023-01-17 22:26 出处:网络
I have a list of strings on the format yyyy.mm.ddThh, I\'d like to create a tree like structure of its components(Years, Months,Days,Hours)

I have a list of strings on the format yyyy.mm.ddThh, I'd like to create a tree like structure of its components(Years, Months,Days,Hours)

e.g. I have a list like:

List<String> l = new List<String>()
l.add("2010.10.11T10");
l.add("2010.10.11T11");
l.add("2010.09.01T23");
l.add("2009.01.02T03");

From this I'd like something like:

new {
     { Year = 2009, 
     开发者_开发百科  Months = { { Month = 01, Days = { {Day = 02, Hours = {{Hour = 03}}}}},
     { Year = 2010
       Months = { { Month = 10, Days = { {Day = 11, Hours = {{Hour = 10,Hour = 11}}}}},
                 { Month = 09, Days = { {Day = 01, Hours = {{ Hour = 23}}}}}
                }

     }

Surely that should be possible with linq ?


Something like this?

var groupedDates = l.Select(date => DateTime.ParseExact(date, "yyyy.MM.dd'T'HH",
                                    CultureInfo.InvariantCulture))
                    .GroupBy(date => date.Year)
                    .Select(yg => new { Year = yg.Key, Months = yg
                        .GroupBy(ydate => ydate.Month)
                        .Select(mg => new { Month = mg.Key, Days = mg
                            .GroupBy(mdate => mdate.Day)
                            .Select(dg => new { Day = dg.Key, Hours = dg
                                .GroupBy(ddate => ddate.Hour)
                                .Select(hg => new { Hour = hg.Key, Values = hg })
                            })
                        })
                    });

In LINQ query syntax (courtesy mostly by .NET Reflector):

var groupedDates =
    from date in
        from date in l
        select DateTime.ParseExact(date, "yyyy.MM.dd'T'HH",
                                   CultureInfo.InvariantCulture)
    group date by date.Year into yg
    select new { Year = yg.Key, Months =
        from ydate in yg
        group ydate by ydate.Month into mg
        select new { Month = mg.Key, Days =
            from mdate in mg
            group mdate by mdate.Day into dg
            select new { Day = dg.Key, Hours =
                from ddate in dg
                group ddate by ddate.Hour into hg
                select new { Hour = hg.Key, Values = hg }
            }
        }
    };
0

精彩评论

暂无评论...
验证码 换一张
取 消