Si8
Si8

Reputation: 9225

How to search in Dictionary with string array as key

So I have set up my Dictionary as follow:

Dictionary<string[], string> d = new Dictionary<string[], string>();
d.Add(new[] { "[email protected]", "[email protected]" }, "Group 1");
d.Add(new[] { "[email protected]", "[email protected]" }, "Group 2");

string keycheck = "[email protected]";
string val = "";

d.TryGetValue(keycheck, out string k);

I get the following error:

Argument 1: cannot convert from 'string' to 'string[]' (CS1503) (Project1)

which make sense since the key in the Dictionary is an String array.

How can I update my code so I can find the value in the Dictionary based on the email string.

So if the keycheck is provided above, the return value should be Group 1

Upvotes: 0

Views: 2615

Answers (3)

Tamir Daniely
Tamir Daniely

Reputation: 1710

The way you're arranging your data you will not be able to query the index at O(1). all searches will be slow. To use Dictionary<TKey, TValue> effectively you need to do something like this:

    class Group : List<string>
    {
        public string Name { get; set; }
        public Group(string name) => Name = name;
    }

    static void Main(string[] args)
    {
        var groups = new List<Group> {
            new Group("Group 1") { "[email protected]", "[email protected]" },
            new Group("Group 2") { "[email protected]", "[email protected]" }
        };


        var index = groups
            .SelectMany(group => group.Select(item => (item, group)))
            .ToDictionary(x => x.item, x => x.group);

        // This will be a very fast operation
        var whichGroup = index["[email protected]"].Name; // = "Group 1"
    }

If your data set gets updated then you'll also need to update the index. For that you can extend Collection<T> which allows you to handle changes with overrides.

Note that this approach means that every value can only be in 1 group. If you need to be able to have the same value in several groups then the index value becomes a list.

Upvotes: 1

Kit
Kit

Reputation: 21709

Use an IDictionary<string, string>. The key is an email address. The value is a group. Add a group for each email address. It’s ok for group to be added more than once. This makes your lookup simple.

Upvotes: 0

Magnetron
Magnetron

Reputation: 8543

var result = d.FirstOrDefault(x=>x.Key.Contains(keycheck));

It returns a KeyValuePair, to get the value you can do a .Value. If it can't find, it will return a KeyValuePair where both the key and value are null.

Note, however, that using an array as the key and search for strings inside the array, you lose one of the greatest benefits of the Dictionary, which is a faster way to retrieve a value, given it's key.

Upvotes: 2

Related Questions