开发者

How do you create a nested LINQ Grouping / Lookups for a Collection of Objects

Given a list of objects with a date and decimal, I would like to index these objects by the开发者_JAVA技巧 year, month, dayofweek and hour of the date. In .NET 2.0, I would have created this graph using a set of nested dictionaries and a list as the leaf node. I am interested in how this could be done with LINQ.


Do you mean something like this?

var grouping = from item in myList
               group item by new { item.Date.Year, item.Date.Month, item.Date.DayOfWeek, item.Date.Hour }
               into groupedItems
               select groupedItems;


Let's assume you have class with DateTime and Decimal properties...

public class SomeThingWithDateAndDecimal
{
    public DateTime SomeDate { get; set; }
    public decimal SomeDecimal { get;set; }
}

If I were you I'd create a class for your key like so...

public class IndexKey
{
    public int Year { get; set; }
    public int Month { get; set; }
    public DayOfWeek DayOfWeek { get; set; }
    public int Hour { get; set; }

    public IndexKey(DateTime dt)
    {
        Year = dt.Year;
        Month = dt.Month;
        DayOfWeek = dt.DayOfWeek;
        Hour = dt.Hour;
    }

Then from your list do something like this...

public static void Main()
{
    var l = new List<SomeThingWithDate>();

    //Fill the list with stuff...

    var indexed = l.ToLookup(o => new IndexKey(o.SomeDate));
}

This isn't nested, but anything you could do with nested dictionaries you can do with this structure. Some things you are difficult to do with nested dictionaries become simpler such as partial key lookup, i.e. "Get all the values with Hour == 2".

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜