-3

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...
}
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
koshi
  • 311
  • 3
  • 8

1 Answers1

3

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

John Wu
  • 50,556
  • 8
  • 44
  • 80