繁体   English   中英

如何在 IDictionary 中查找特定值<string, object> ?

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

这个IDictionary<string, object>包含我登录到 mongodb 的用户数据。 问题是TValue是一个复杂的对象。 TKey只是类名。

例如:

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; }
}

目前,我正在尝试遍历Dictionary并比较类型,但无济于事。 有没有更好的方法来做到这一点,还是我错过了标记?

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

只需使用OfType<>() 你甚至不需要钥匙。

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);
}

输出:

Foo
123
Bar

链接到小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM