Linq ToDictionary returns an anonymous type
I want to call a method that returns an anonymous type. I need to know what the Type of this anonymous type is because I am returning it in a method. Is it called "dynamic"? When I debug, the watch window says the type is <>f__AnonymousType0.
Here is my code:
// this doesn't compile
public static Dictionary<int,dynamic> GetRuleNamesDictionary()
{
List<ResponseRoutingRule> 开发者_StackOverflow社区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; }
...
}
Well, you actually seem to be returning a Dictionary<int, string>
. The type of dict
's values isn't an anonymous type; it's a plain old string
. In fact, there doesn't seem to be any need for anonymous types or dynamic
here.
Are you sure this isn't what you really want?
public static Dictionary<int, string> GetRuleNamesDictionary()
{
return GetResponseRoutingRules()
.ToDictionary(r => r.ResponseRoutingRuleId, r => r.RuleName);
}
If not, please let us know why.
If you really want to stick with dynamic
, you could of course cast as appropriate:
public static Dictionary<int, dynamic> GetRuleNamesDictionary()
{
return GetResponseRoutingRules()
.ToDictionary(r => r.ResponseRoutingRuleId, r => (dynamic) r.RuleName);
}
It's an object. If you need strong typing, don't make it anonymous.
What I really want to do is return a dynamic type with 2 properties called ResponseRoutingRuleId
and RuleName
. This is so I can assign it to an MVC select list and specify the dataValue
field and the dataText
field.
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 am getting this dynamic object but I don't know what return type to specify in GetRuleObject()
.
精彩评论