How to find a specific value in an IDictionary<string, object>?

4.3k Views Asked by At

This IDictionary<string, object> contains user data I'm logging into mongodb. The issue is the TValue is a complex object. The TKey is simply the class name.

For example:

public class UserData
{
    public string FirstName { get; set; }
    public string LastName  { get; set; }
    public Admin NewAdmin   { get; set; }
}    
public class Admin
{
    public string UserName { get; set; }
    public string Password { get; set; }
}

Currently, I'm trying to iterate through the Dictionary and compare types but to no avail. Is there a better way of doing this or am I missing the mark?

var argList = new List<object>();
foreach(KeyValuePair<string, object> kvp in context.ActionArguments)
{
    dynamic v = kvp.Value;
    //..compare types...
}
1

There are 1 best solutions below

0
On BEST ANSWER

Just use OfType<>(). You don't even need the key.

public static void Main()
{
    var d = new Dictionary<string,object>
    {
        { "string", "Foo" },
        { "int", 123 },
        { "MyComplexType", new MyComplexType { Text = "Bar" } }
    };

    var s = d.Values.OfType<string>().Single();
    var i = d.Values.OfType<int>().Single();
    var o = d.Values.OfType<MyComplexType>().Single();

    Console.WriteLine(s);
    Console.WriteLine(i);
    Console.WriteLine(o.Text);
}

Output:

Foo
123
Bar

Link to Fiddle