Hi Arjang,
What about this:
private Func<IQueryable<Product>, IQueryable<Product>> _getBoiFg =
qs => from c in qs
where c.DATAAREAID == "boi" && c.ITEMGROUPID == "fg"
select c;
public List<Product> GetAll()
{
using (var ctx = new DataEntities())
{
return _getBoiFg(ctx.Products).ToList();
}
}
public List<Product> GetAllContaining(string needle)
{
using (var ctx = new DataEntities())
{
return (from c in _getBoiFg(ctx.Products)
where c.Id.Contains(needle) ||
c.Name.Contains(needle)
select c).ToList();
}
}
I would recommend against returning a List<T>. Instead returning a T[] is
better. It implies less functionality than List<T> while still ensuring that
the query is executed.
You also used a syntax which made the code misleading with the {} looking
like the declaration of the DataEntities was in a using statement.
Cheers.
James.
-----Original Message-----
From: [email protected] [mailto:[email protected]]
On Behalf Of Arjang Assadi
Sent: Tuesday, 13 July 2010 16:32
To: ozDotNet
Subject: Refactoring linq Query Expression
Greetings,
I am trying to factor out the qry from GetAll and reuse it (instead of
copy and pasting ) in GetAllContaining(needle).
Here is the code: (any other points is also welcomed :)
public class Product
{
public List<Product> GetAll()
{
DataEntities ctx = new DataEntities();
{
var qry = from c in ctx.Products
where c.DATAAREAID == "boi" && c.ITEMGROUPID == "fg"
select c;
return qry.ToList();
}
}
public List<Product> GetAllContaining(string needle)
{
DataEntities ctx = new DataEntities();
{
var qry = from c in ctx.Products
where (c.DATAAREAID == "boi" && c.ITEMGROUPID == "fg")
&&
(c.Id.Contains(needle) || c.Name.Contains(needle))
select c;
return qry.ToList();
}
}
}
Thank you
Arjang