1

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

Neaox
  • 1,933
  • 3
  • 18
  • 29

1 Answers1

4

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.

Ani
  • 111,048
  • 26
  • 262
  • 307
  • In your opinion what is the difference/advantage/disadvantage of using `new` to create an anonymous typed object as apposed to `Tuple.Create` in this case? – Neaox May 30 '14 at 05:53
  • 1
    I chose the anon type for readability (esp. since this is SO and readers may have varying skill levels around these concepts). It's a little more verbose, but easier to follow than Item1, Item2 etc. If it's clear in context, there's nothing wrong with Tuple.Create IMO . – Ani May 30 '14 at 05:55