重构几乎相同的 linq 查询,其中 where 子句不同

发布于 2024-12-25 16:08:48 字数 525 浏览 1 评论 0原文

我有两种几乎相同的方法。唯一的区别是 where 子句(和方法名称)。我刚刚包含了一个简化的 linq 查询。

from tableA in db.tableA
join tableB in db.tableB on tableA.id equals tableB.id
where tableB.ref == "blah"
select tableA

from tableA in db.tableA
join tableB in db.tableB on tableA.id equals tableB.id
where tableB.refb == "blah"
select tableA

有什么方法可以改变位置 ?我知道我可以从查询中删除 where ,然后在返回结果后使用 .notation 进行过滤。 (可能需要做一些其他的事情来确保返回 tableB 中我需要的字段)。

有更好的办法吗?我有两个除了 where 之外几乎相同的 linq 查询,这有什么关系吗?

I have two methods that are almost identical. The only dffernece is the where clause (and method name). I have just included a simplified linq query.

from tableA in db.tableA
join tableB in db.tableB on tableA.id equals tableB.id
where tableB.ref == "blah"
select tableA

and

from tableA in db.tableA
join tableB in db.tableB on tableA.id equals tableB.id
where tableB.refb == "blah"
select tableA

Is there a way I can make the where change? I know I could remove there where from the query then after the results are returned use .notation to filter. (May need to do some other stuff to make sure the field I need from tableB is returned).

Is there a better way? Does it matter that I have two linq queries that are almost identical apart from the where?

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

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

发布评论

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

评论(2

半世蒼涼 2025-01-01 16:08:48

是的,将其重构为这样,

var data = from tableA in db.tableA
           join tableB in db.tableB on tableA.id equals tableB.id
           select tableA

var one = data.Where(x=>x.ref == "blah");
var two = data.Where(x=>x.refb == "blah");

这样您就可以在一个地方进行查询并仅过滤该主查询

Yes refactor it to this

var data = from tableA in db.tableA
           join tableB in db.tableB on tableA.id equals tableB.id
           select tableA

var one = data.Where(x=>x.ref == "blah");
var two = data.Where(x=>x.refb == "blah");

This way you can you query in one palce and just filter that main query

这个俗人 2025-01-01 16:08:48

除非性能是一个问题,否则您可以将它们保持原样。
这些看起来像是简单的查询,重构它们会降低代码的可读性。

Unless performance is a concern, you could keep them as they are now.
These look like simple queries and refactoring them would make the code less readable.

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