Raveendra M Pai
Raveendra M Pai

Reputation: 445

.Net : multiple keys to list of values

I am looking for data structure or optimized code snippet which helps me to store multiple keys mapping to a list of string values and also how efficiently we can access list values using any one of the key from multiple keys pool.

Let me put these in a sample example. say keys are "Hi, "Hello", "how are you ?" maps to VALUES "1234", "56789", "34567"

now is it possible for me to fetch the VALUES list (all 3 elements) using any one of the keys like "Hi" or "Hello" or "how are you ?" in a single statement.

I am trying to avoid looping through the keylist to match the key.

Upvotes: 1

Views: 1958

Answers (1)

Gilad Green
Gilad Green

Reputation: 37299

Use a Dictionary<string, List<string> where the different keys that map to the same list share the same reference of the list.

For your example above:

var values = new List<string> { "1234", "56789", "34567" };
var mapping = new Dictionary<string, List<string>>
{
    ["Hi"] = values,
    ["Hello"] = values,
    ["how are you ?"] = values
};

Then accessing through the indexer will retrieve the same reference for all those keys (mapping["Hi"] == mapping["Hello"]).


If you have your data in the form of a list of keys and values then you can use the following to create the flattened dictionary for it:

var rawData = new List<(List<string> keys, List<string> values)>
{
    (new List<string> {"Hi", "Hello", "how are you ?" }, new List<string> {"1234", "56789", "34567" })
};

var result = rawData.SelectMany(item => item.keys.Select(k => (k, item.values)))
                    .ToDictionary(key => key.k, val => val.values);

Note that for ease of writing I used the named tuples of C# 7.0. Of course it can be also done with custom classes or with anonymous types in the linq part

See that when constructing the data structure it does look through all the keys so it is still an O(n) operation but then accessing a value using any of the keys is an O(1) operation.

Upvotes: 1

Related Questions