views:

57

answers:

2

Given a list of objects with a date and decimal, I would like to index these objects by the 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.

+1  A: 

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;
Dave
Using an anonymous type means you can't pass this grouping around to any other classes or functions. I think it's better to create a specific class for your key so the grouping can be used project wide...
Jason Punyon
True you can't pass it around, but I'd leave creating that class until I knew I needed to pass it around. I'd also be hesitant to use it as a replacement for the key without knowing whether it's going to be used as part of a LinqToSql query.
Dave
That works perfectly. I do not currently do not need to pass it around, but I will keep the spec index class in mind for future reference.
Jeff Windsor
+1  A: 

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".

Jason Punyon