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
}
}
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With