【问题标题】:How to find a specific value in an IDictionary<string, object>?如何在 IDictionary<string, object> 中查找特定值?
【发布时间】:2018-08-22 20:48:00
【问题描述】:

这个IDictionary&lt;string, object&gt; 包含我正在登录 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...
}

【问题讨论】:

  • "更好的方法..." 更好的方法,究竟是什么?您描述了您的解决方案,但没有描述您的问题。
  • 您到底想在 ActionArguements 中找到什么?
  • 您是否保证键(类名)意味着集合中每种类型的类都只有一个?我不确定你想在这里做什么......

标签: c# .net .net-core idictionary onactionexecuting


【解决方案1】:

只需使用OfType&lt;&gt;()。你甚至不需要钥匙。

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

Link to Fiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 2022-06-22
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多