C# ToDictionary 在 C# 7 之前获取匿名类型值

标签 c# .net anonymous-types

你好这里是我如何从 C# 7 之后的字典 myage 值中获取值

 static void Main(string[] args)
    {
        List<User> userlist = new List<User>();
        User a = new User();
        a.name = "a";
        a.surname = "asur";
        a.age = 19;

        User b = new User();
        b.name = "b";
        b.surname = "bsur";
        b.age = 20;

        userlist.Add(a);
        userlist.Add(b);

        var userlistdict = userlist.ToDictionary(x => x.name,x=> new {x.surname,x.age });

        if(userlistdict.TryGetValue("b", out var myage)) //myage

        Console.WriteLine(myage.age);

    }  
}
public class User {
    public string name { get; set; }
    public string surname { get; set; }
    public int age { get; set; }
}

好的结果是:20

但在 C# 7 之前,我如何从字典中获取 myage 值。我找不到任何其他方法。只是我在 trygetvalue 方法中找到了 declare myage。

最佳答案

三个选项:

首先,您可以像这样编写一个扩展方法:

public static TValue GetValueOrDefault<TKey, TValue>(
    this IDictionary<TKey, TValue> dictionary,
    TKey key)
{
    TValue value;
    dictionary.TryGetValue(dictionary, out value);
    return value;
}

然后称它为:

var result = userlist.GetValueOrDefault("b");
if (result != null)
{
    ...
}

其次,您可以通过提供虚拟值将 varout 一起使用:

var value = new { surname = "", age = 20 };
if (userlist.TryGetValue("b", out value))
{
    ...
}

或者根据评论:

var value = userlist.Values.FirstOrDefault();
if (userlist.TryGetValue("b", out value))
{
    ...
}

第三,你可以先使用ContainsKey:

if (userlist.ContainsKey("b"))
{
    var result = userlist["b"];
    ...
}

关于C# ToDictionary 在 C# 7 之前获取匿名类型值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46892111/

相关文章:

c# - 为什么 Enum.GetValues() 在使用 "var"时返回名称?

C# -Mono(平台独立性)

c# - 在.NET Remoting 中如何知道类方法是在内部调用还是远程调用?

c# - 使用 C# 进行内容感知图像裁剪

c++ - 在 C++ 函数中返回匿名实例/值

entity-framework - 加入 Entity Framework 和 F#

c# - 使用 C# 设置全局热键

c# - 浏览器打开,但无法加载本地主机页面——Selenium、MVC、C# .NET

c# - 遍历结构?

C# WPF : Listbox with drag to select text