sonertbnc
sonertbnc

Reputation: 1720

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.

Upvotes: 4

Views: 1376

Answers (2)

Shyju
Shyju

Reputation: 218752

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);

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500825

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"];
    ...
}

Upvotes: 7

Related Questions