Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# ToDictionary get Anonymous Type value before C # 7

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.

like image 907
sonertbnc Avatar asked Oct 23 '17 14:10

sonertbnc


2 Answers

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"];
    ...
}
like image 193
Jon Skeet Avatar answered Oct 27 '22 11:10

Jon Skeet


Another option is to store the User object as the dictionary item value instead of the anonymous type and then you can declare the type first and use that in the 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);
}

The first line of creating the Dictionary from the list is same as

 var userlistdict = userlist.ToDictionary(x => x.name);
like image 32
Shyju Avatar answered Oct 27 '22 09:10

Shyju