RamaRaunt RamaRaunt -4 years ago 78
C# Question

How do you find a value in a dictionary, given a stack of classes that contain dictionaries?

I have a problem with classes. I need to do something, but can't figure out a solution.

Each class1 has a dictionary with string keys and class2 values. I know for a fact that there are no two dictionary keys in any class1 that match. How would I find a certain class2 in a stack of class1, given the key?

Answer Source

Assuming these classes:

public class Class1
{
    public Dictionary<string, Class2> ClassTwos { get; private set;}
    public Class1()
    {
        ClassTwos = new Dictionary<string, Class2>();
    }
}

public class Class2 {}

If you have multiple instances of Class1 each with its own Dictionary<string,Class2> then you can't guarantee that the same key won't appear in multiple dictionaries. You can only be sure that it won't appear twice in the same dictionary. So if you're looking in a set of Class1 for a certain key, you could get more than one result.

Assuming you only want the first result:

(There are ways to do this with LINQ, but this illustrates more clearly what's happening.)

Class2 FindClassTwoByKey(Stack<Class1> stack, string key)
{
    foreach (var class1 in stack)
    {
        if (class1.ClassTwos.ContainsKey(key))
        {
            // We found a match. Return it. We're done.
            return class1.ClassTwos[key];
        }
    }
    return null;
}

Or if you wanted to return all of the matches:

List<Class2> FindClassTwosByKey(Stack<Class1> stack, string key)
{
    var result = new List<Class2>();
    foreach (var class1 in stack)
    {
        if (class1.ClassTwos.ContainsKey(key))
        {
            result.Add(class1.ClassTwos[key]);
        }
    }
    return result;
}

Or if you want to do it using LINQ, because it's harder to read but sort of fun,

Class2 FindClassTwoByKey(Stack<Class1> stack, string key)
{
    return stack.Where(s => s.ClassTwos.ContainsKey(key))
        .Select(s => s.ClassTwos[key])
        .FirstOrDefault();
}

List<Class2> FindClassTwosByKey(Stack<Class1> stack, string key)
{
    return stack.Where(s => s.ClassTwos.ContainsKey(key))
            .Select(s => s.ClassTwos[key])
            .ToList();
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download