Linq ToDictionary returns an anonymous type

I want to call a method that returns an anonymous type. I need to know what Type of anonymous type is, because I return it in the method. Is this called "dynamic"? When I debug, the viewport says that type is <> f__AnonymousType0.

Here is my code:

// this doesn't compile
public static Dictionary<int,dynamic> GetRuleNamesDictionary()
{
    List<ResponseRoutingRule> rules = GetResponseRoutingRules();    
    var q = (rules.Select(r => new {r.ResponseRoutingRuleId, r.RuleName}));

    var dict1 = q.ToDictionary(d => d.ResponseRoutingRuleId);
    var dict = q.ToDictionary(d => d.ResponseRoutingRuleId, d => d.RuleName);
    return dict;
}

public static List<ResponseRoutingRule> GetResponseRoutingRules()
{
   ....
}


public class ResponseRoutingRule
{
    public int ResponseRoutingRuleId { get; set; }
    ....
    public string RuleName { get; set; }
    ...
}
+3
source share
3 answers

Well, you are actually coming back Dictionary<int, string>. The value type is dictnot an anonymous type; it's plain old string. In fact, it seems that there are no anonymous types or dynamic.

Are you sure this is not what you really want?

public static Dictionary<int, string> GetRuleNamesDictionary()
{
    return GetResponseRoutingRules()
            .ToDictionary(r => r.ResponseRoutingRuleId, r => r.RuleName);    
}

If not, let us know why.

dynamic, , , :

public static Dictionary<int, dynamic> GetRuleNamesDictionary()
{
    return GetResponseRoutingRules()
            .ToDictionary(r => r.ResponseRoutingRuleId, r => (dynamic) r.RuleName);    
}
+3

. , .

0

I really want to return a dynamic type with two properties called ResponseRoutingRuleIdand RuleName. This means that I can assign it to the MVC selection list and specify a field dataValueand a field dataText.

SomeMethod(){
    List<{my dynamic type}> ruleObject = GetRuleObject();

    var ruleSelectList = new Web.Mvc.SelectList (ruleObject, "ResponseRoutingRuleId", "RuleName");
}

List<{my dynamic type}> GetRuleObject(){...}

In my Linq query, I get this dynamic object, but I don't know what type of return value to point to GetRuleObject().

0
source

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


All Articles