LINQ:将查询表达式转换为使用 lambda

发布于 2024-08-24 10:54:53 字数 422 浏览 4 评论 0原文

我正在尝试将 LINQ To Entities 查询重写为表达式。我的模型是一所可以有很多人的学校。人员继承给教师、学生等。

以下查询对我有用:

IQueryable<DAL.TEACHER> teacher = 
from p in School 
select p.PERSON as ESBDAL.TEACHER;

我如何将其写为查询表达式?我的想法是这样的:

IQueryable<DAL.TEACHER> teacher = 
School.Select(x=>x.PERSON) as IQueryable<DAL.TEACHER>;

不幸的是这个声明不起作用。我是否误解了 .Select()

I'm trying to rewrite a LINQ To Entities query to an expression. My model is a School which can have many Persons. Persons are inherited out to teachers, students, etc.

The following query works for me:

IQueryable<DAL.TEACHER> teacher = 
from p in School 
select p.PERSON as ESBDAL.TEACHER;

How would I write this as a query expression? I thought something like:

IQueryable<DAL.TEACHER> teacher = 
School.Select(x=>x.PERSON) as IQueryable<DAL.TEACHER>;

Unfortunately this statement doesn't work. Am I misunderstanding the .Select()?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

霞映澄塘 2024-08-31 10:54:53

它实际上应该是:

School.Select(x => x.PERSON as DAL.TEACHER)

记住,您正在尝试将 PERSON 转换为 TEACHER,因此它会进入委托内部School.Select(x => x.PERSON) 本身的结果实际上是一个 IEnumerable,它不能转换为 IEnumerable;

另一件事 - 如果某些 PERSON 实例实际上不是 TEACHER(即它们是 STUDENT),那么您最终会输出中包含 null 引用。如果 PERSON 可以是多种类型,您可能会想这样写出来:

School.Select(x => x.PERSON).OfType<DAL.TEACHER>();

这实际上会过滤掉所有 PERSON 实体t TEACHER,因此您只能返回序列中的 TEACHER 实例(无空值)。

另请注意,from x in y 语法是“查询”(特别是查询理解语法)。第二种形式是 lambda 语法。

It should actually be:

School.Select(x => x.PERSON as DAL.TEACHER)

Remember, you're trying to cast the PERSON to a TEACHER, so it goes inside the delegate. The result of School.Select(x => x.PERSON) by itself is actually an IEnumerable<PERSON>, which is not convertible to IEnumerable<TEACHER>.

One more thing - if some PERSON instances are not actually TEACHERs (i.e. they are STUDENTs instead), you're going to end up with null references in the output. If PERSON can be more than one type, you would probably want to write it out like this instead:

School.Select(x => x.PERSON).OfType<DAL.TEACHER>();

This will actually filter out all of the PERSON entities that aren't TEACHERs, so you only get back TEACHER instances in the sequence (no nulls).

Also note that the from x in y syntax is the "query" (specifically query comprehension syntax). The second form is lambda syntax.

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