.netlinqindexinglookupilookup

ILookup store item under multiple keys


I have a situation where I have a set of objects, these objects relate to items in a database. We create a local cache of these objects along with indexes to allow fast filtering/searching of the data. The issue I am having is converting the list of the objects to a lookup.

the (very) simplified object:

String ItemID;
List<String> LocationIDs;

An item can belong to multiple locations and each location can contain multiple items.

I am wanting to create a lookup using the LocationIDs as keys so that I get a list of items belonging to a specific location using its location id, and any item can be found under any number of locations (keys of the lookup).

I tried the following

items.ToLookup(item => item.LocationIDs);

But this doesn't return the desired result.

The ideal usage would be:

Lookup:

{
    ["Location 1"] => {
        {Item 1},
        {Item 2},
        {Item 3},
        {Item 9},
    },
    ["Location 2"] => {
        {Item 2},
        {Item 4},
        {Item 3}
    },
    ["Location 3"] => {
        {Item 1},
        {Item 3},
        {Item 7}
    },
    ["Location 4"] => {
        {Item 1},
        {Item 2},
        {Item 10}
    }
}

Then you could easily retrieve the items for a given location.

Any help is appreciated.

Thanks


Solution

  • Assuming it needs to be from LocationID -> ItemID, one way would be:

    items.SelectMany(item => item.LocationIDs,
                     (item, locationID) => new { item.ItemID, LocationID = locationID })
         .ToLookup(tuple => tuple.LocationID, tuple => tuple.ItemID)
    

    This first flattens all your data to a sequence of (itemID, locationID) tuples before turning that into a lookup.

    It's a trivial modification to the above if the lookup needs to be from the LocationID -> Item object itself.