如何在 IDictionary<string, object> 中查找特定值?
How to find a specific value in an IDictionary<string, object>?
此 IDictionary<string, object>
包含我正在登录 mongodb 的用户数据。问题是 TValue
是一个复杂的对象。 TKey
只是 class 名称。
例如:
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
此 IDictionary<string, object>
包含我正在登录 mongodb 的用户数据。问题是 TValue
是一个复杂的对象。 TKey
只是 class 名称。
例如:
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