非泛型 IQueryable 枚举问题

发布于 2024-07-14 06:35:47 字数 824 浏览 6 评论 0原文

使用动态 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

落叶缤纷 2024-07-21 06:35:47

当您的查询在运行时解析时,您不能期望动态对象的类型在编译时解析。 这就是动态 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.

暮色兮凉城 2024-07-21 06:35:47

如果 IEnumerable 不是通用的,那么您应该进行强制转换而不是使用反射。

If the IEnumerable is not generic then you ought to cast rather than use reflection.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文