Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check for string values in a Dictionary<string, List<string[]>>() object?

Tags:

c#

dictionary

To keep it simple, I have the following Dictionary that I fill with an unknown amount of strings for every string key. I also have the following list of strings.

var dict = new Dictionary<string, List<string[]>>();
IList<string> headerList = new List<string>();

How can I check if a string from the list is a value in the dictionary? My data looks like similar to this:

 Key           Value
 -----         ------------------
 Car           honda, volks, benz
 Truck         chevy, ford

I need to check if "honda", for example, is a contained int the dictionary values. I am thinking I need to do something like the following to see if the values contain a list, which contain the string in question. Keep in mind I am fairly new to C#.

    foreach (string header in headerList)
    {
        // This is wrong, I don't know what to put in the if statement 
        if (dict.ContainsValue(r => r.Contains(header)))
        {
            // do stuff 
        }
    }
like image 739
kmk09k Avatar asked Apr 24 '15 20:04

kmk09k


2 Answers

John Odom is correct, you need a List.

What I would suggest is that you use a HashSet<string> internally for the value of the Diictionary. E.g. Dictionary<string, HashSet<string>>

Then when it comes to querying it you can do something like this:

 headerList.Where(x => dict.Values.Any(d => d.Contains(x))).ToList()

Have a look at .NET Nested Loops vs Hash Lookups for a performance comparison

like image 126
Michal Ciechan Avatar answered Oct 31 '22 21:10

Michal Ciechan


If you only want to know if the dictionary contains the car bran (e.g. "honda") you can use this query:

bool isInDict = dict.Values
                    .SelectMany(lst => lst)
                    .Any(car => car == "honda");

To return the key under which the value is stored you can use something like this:

string containingKey = dict.Keys
                           .Where(key => dict[key].Contains("honda"))
                           .FirstOrDefault();

And to get the whole list in which the value occurs run this:

List<string> containingList = dict.Values
                                  .Where(v => v.Contains("honda"))
                                  .FirstOrDefault();

In the first case all you do you flatten all the lists and check them all if any value is the searched car name. If true the value is in the dictionary.

Second one: get all the keys. Apply each key to the dictionary to get respective list and check the list if it contains the car name. Return the first key under which the car name has been found.

Third one - similar to the second one, but we run the search on the values. Check if the value (i.e. List) contains the car name. Return the first collection that does contain the name.

like image 37
PiotrWolkowski Avatar answered Oct 31 '22 22:10

PiotrWolkowski