Imran Rizvi
Imran Rizvi

Reputation: 7438

Dictionary as a Lookup value

To have a holiday calculation I have to load holidays from repository for a year and for multiple countries and their state.

To get good performance in a logic where I need to check if a date is holiday or not, I am trying to convert a list to lookup using .ToLookup extension with a dictionary as a value of it.

This Dictionary will have State as a key and HashSet for that state as a value.

I am trying to create it using Lookup, Dictionary and HashSet, so that I can quickly reach to holiday info by filtering it using Country and State.

following is the code:

var CountryStateHolidayLookup = holidays.ToLookup(x => x.Country,
            x => (
        new Dictionary<int, HashSet<Holiday>>()
               { { x.State,
                    new HashSet<Holiday>()
                    { new Holiday(
                        x.HolidayDate.Date, x.IsWeekend)
                    }
                } }
       )
       );

in the output of above code I get a Lookup with country code , value of this lookup is coming an enumerable of Dictionary with each holiday as a new dictionary.

whereas I was expecting a dictionary with all item as one HashSet

I know I am doing something wrong here , What changes I have to do ?

Upvotes: 0

Views: 475

Answers (1)

Jeff Mercado
Jeff Mercado

Reputation: 134841

I think you have it backwards. A lookup can be thought of as a multi-valued dictionary. You'll want country key in to the lookup of states.

You probably want something like this:

var CountryStateHolidayLookup = holidays.GroupBy(h => h.Country)
    .ToDictionary(
        g => g.Key,
        g => g.ToLookup(
            h => h.State,
            h => new Holiday(h.HolidayDate.Date, h.IsWeekend)
        )
    );

Upvotes: 2

Related Questions