Linq ToDictionary 返回匿名类型
我想调用一个返回匿名类型的方法。我需要知道这个匿名类型的类型是什么,因为我在方法中返回它。这也叫“动态”吗?当我调试时,监视窗口显示类型为 <>f__AnonymousType0。
这是我的代码:
// 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; }
...
}
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> 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; }
...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,您实际上似乎返回了一个
Dictionary
。dict
值的类型不是匿名类型;这是一个普通的旧字符串
。事实上,这里似乎不需要匿名类型或dynamic
。你确定这不是你真正想要的吗?
如果没有,请告诉我们原因。
如果您真的想坚持使用
动态
,您当然可以根据需要进行强制转换:Well, you actually seem to be returning a
Dictionary<int, string>
. The type ofdict
's values isn't an anonymous type; it's a plain oldstring
. In fact, there doesn't seem to be any need for anonymous types ordynamic
here.Are you sure this isn't what you really want?
If not, please let us know why.
If you really want to stick with
dynamic
, you could of course cast as appropriate:它是一个物体。如果您需要强类型,请不要使其匿名。
It's an object. If you need strong typing, don't make it anonymous.
我真正想做的是返回一个具有 2 个属性的动态类型,分别为 ResponseRoutingRuleId 和 RuleName。这样我就可以将其分配给 MVC 选择列表并指定
dataValue
字段和dataText
字段。在我的 Linq 查询中,我得到了这个动态对象,但我不知道在
GetRuleObject()
中指定什么返回类型。What I really want to do is return a dynamic type with 2 properties called
ResponseRoutingRuleId
andRuleName
. This is so I can assign it to an MVC select list and specify thedataValue
field and thedataText
field.In my Linq query, I am getting this dynamic object but I don't know what return type to specify in
GetRuleObject()
.