John
John

Reputation: 487

Refactoring near identical linq queries where the where clause is different

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?

Upvotes: 1

Views: 135

Answers (2)

Leigh Ciechanowski
Leigh Ciechanowski

Reputation: 1317

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

Upvotes: 2

Arnold Zokas
Arnold Zokas

Reputation: 8580

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.

Upvotes: 1

Related Questions