非泛型 IQueryable 枚举问题
使用动态 linq (
var query =
db.Customers.Where("City == @0 and Orders.Count >= @1", "London", 10).
OrderBy("CompanyName").
Select("New(CompanyName as Name, Phone)");
foreach (var item in query)
{
foreach (var prop in item.GetType().GetProperties())
{
Console.WriteLine(prop);
}
}
尝试转换但出现错误无法将类型“DynamicClass1”的对象转换为类型“Test”。
foreach (var item in query)
{
Console.WriteLine("{0}: {1}", ((Test)item).CompanyName, ((Test)item).Phone);
}
public class Test {
public string CompanyName { get; set; }
public string Phone { get; set; }
}
Using dynamic linq (http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx) I run the query below which returns an IQueryable. On this result which is also an IEnumerable I am able to run a Count() however there is not ToList() to get the values. I can enumerate over them using a foreach but am not able to access the individual fields in the resultant anonymous type without reflection. Is this the only way? Thanks
var query =
db.Customers.Where("City == @0 and Orders.Count >= @1", "London", 10).
OrderBy("CompanyName").
Select("New(CompanyName as Name, Phone)");
foreach (var item in query)
{
foreach (var prop in item.GetType().GetProperties())
{
Console.WriteLine(prop);
}
}
Tried casting but got an error Unable to cast object of type 'DynamicClass1' to type 'Test'.
foreach (var item in query)
{
Console.WriteLine("{0}: {1}", ((Test)item).CompanyName, ((Test)item).Phone);
}
public class Test {
public string CompanyName { get; set; }
public string Phone { get; set; }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您的查询在运行时解析时,您不能期望动态对象的类型在编译时解析。 这就是动态 linq 的全部内容:它允许您以编译时检查为代价执行动态查询。
至少在 C# 4 之前,您必须使用反射来访问动态类型的属性。
You can't expect the type of you dynamic object to be resolved at compile time when your query is resolved at runtime. That's what dynamic linq is all about : it allows you to execute dynamic queries at the cost compile-time checking.
You have to use reflection to access properties of a dynamic type, at least until C# 4.
如果 IEnumerable 不是通用的,那么您应该进行强制转换而不是使用反射。
If the IEnumerable is not generic then you ought to cast rather than use reflection.