Hello here is how i get value from dictionary myage value after C# 7
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; }
}
Okey result is:20
But Before C# 7 how can i get myage value from dictionary. I could't find any other way.Just i found declare myage in trygetvalue method.
Three options:
First, you could write an extension method like this:
public static TValue GetValueOrDefault<TKey, TValue>(
this IDictionary<TKey, TValue> dictionary,
TKey key)
{
TValue value;
dictionary.TryGetValue(dictionary, out value);
return value;
}
Then call it as:
var result = userlist.GetValueOrDefault("b");
if (result != null)
{
...
}
Second, you could use var
with out
by providing a dummy value:
var value = new { surname = "", age = 20 };
if (userlist.TryGetValue("b", out value))
{
...
}
Or as per comments:
var value = userlist.Values.FirstOrDefault();
if (userlist.TryGetValue("b", out value))
{
...
}
Third, you could use ContainsKey
first:
if (userlist.ContainsKey("b"))
{
var result = userlist["b"];
...
}
See more on this question at Stackoverflow