你好这里是我如何从 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)
{
...
}
其次,您可以通过提供虚拟值将 var
与 out
一起使用:
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/