Steve
Steve

Reputation: 103

Find value in dictionary of type <string, string[]>

Here is the code I already have, which works:

private string GetRegionByStore(string store)
{
    foreach (string items in d.Keys)
    {
        if (d[items].Contains(store))
        {
            return items;
        }
    }

    return null;
}

This searches for a key in a dictionary like this:

d.Add("4Q", new string[] { "27", "49", "198", "214", "226", "347", "351", "361", "439", "449", "613", "657", "662", "685" });

There are many entries like 4Q, 4Z, 4J and so on, and each have a string[] with numbers inside. There will never be the same number in another entry, so no worry of duplicates.

The method I am using now currently works, but it feels very hacky and like it is bad practice. Is there a LINQ query I can do to achieve the same thing?

To summarize: Find a number within each dictionary(?), and if it exists, return the key.

Upvotes: 1

Views: 820

Answers (3)

Jose Rodriguez
Jose Rodriguez

Reputation: 10182

You can use this version code:

private string GetRegionByStore(string store)
{
     d.Keys.FirstOrDefault(k => d[k].Contains(store));
}

To find all keys in dictionary:

private string GetRegionByStore(string store)
{
     d.Keys.Where(k => d[k].Contains(store)).ToList();
}

Upvotes: 3

user1548266
user1548266

Reputation:

Something like:

  var strores = d.Where(e => e.Value.Contains("27")).Select(e => e.Key).ToList();

The above will return a list of Keys from your Dictionary<string, string[]> collection where the Value of the collection is found to contain the string you have searched for.

Upvotes: 2

haim770
haim770

Reputation: 49115

Using Linq:

d.Single(x => x.Value.Contains("198")).Key // would return "4Q" in your example

Upvotes: 0

Related Questions