C # ToDictionary gets anonymous type value before C # 7

Hello, here is how I can get the value of myage dictionary 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: 20

But before C # 7, how can I get the value of myage from a dictionary. I could not find another way. I just found the myage declaration in the trygetvalue method.

+4
source share
3 answers

Three options:

First, you can write an extension method as follows:

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

Then name it like:

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

Secondly, you can use varwith out, specifying a dummy value:

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

Or according to the comments:

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

Thirdly, first you can use ContainsKey:

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

you need to create something like

var value = new { surname = "", age = 10 };

if (userlist.TryGetValue("b", out value))
{

}
+1
source

- User , TryGetValue.

var userlistdict = userlist.ToDictionary(x => x.name, x =>  x );

User user;
if (userlistdict.TryGetValue("b",  out user))
{
    Console.WriteLine(user.surname);
    Console.WriteLine(user.age);
}

,

 var userlistdict = userlist.ToDictionary(x => x.name);
0

Source: https://habr.com/ru/post/1688019/


All Articles