相关文章推荐
大力的面包  ·  python tkinter ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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...
                "Better way of doing this..." Better way of doing what, exactly? You described your solution but not your problem.
– John Wu
                Aug 22, 2018 at 20:50
                Are you guaranteeing that the key (class name) means that there is only ever one of each type of class in the collection? I'm not sure what you are trying to do here...
– Ron Beyer
                Aug 22, 2018 at 20:50
        { "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:

Link to Fiddle

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.