【问题标题】:Refactoring near identical linq queries where the where clause is different在 where 子句不同的地方重构接近相同的 linq 查询
【发布时间】:2012-02-04 06:05:37
【问题描述】:

我有两种几乎相同的方法。唯一的区别是 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 查询是否重要?

【问题讨论】:

  • 这些需要单独调用吗?你能不能用 where tableB.ref == "blah" || tableB.refb == "废话"

标签: linq refactoring dry


【解决方案1】:

是的,将其重构为这个

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");

这样您就可以在一个地方进行查询,然后只过滤该主要查询

【讨论】:

  • 这可能会影响性能,因为您正在对完整结果集(由上一个查询返回)执行内存中的子查询。
  • @ArnoldZokas 不,你不是。查询尚未执行。
  • 同意它决定两个编织中较小的那个
  • Where 需要大写 W 顺便说一句。
  • @Leigh:这行不通,因为TableA 不包含属性refrefb
【解决方案2】:

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

【讨论】:

  • 我不同意如果您必须更改查询,您将不得不在多个地方进行更改:(
  • 我会说这取决于使用和性能要求。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-28
  • 2010-10-28
  • 1970-01-01
  • 2020-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多