I have a method BuildQuery that dynamically generates a query. It works well for SQL:
static MyType[] GetDataFromDB(MyDataContext db, string city, string district, string region, string country, string zip)
{
var q = BuildQuery(db.MyTable.AsQueryable(), city, district, region, country, zip);
return q.ToArray();
}
private static IQueryable<MyType> BuildQuery(IQueryable<MyType> q, string city, string district, string region, string country, string zip)
{
if (!string.IsNullOrEmpty(city))
q = q.Where(p => p.City.Contains(city));
if (!string.IsNullOrEmpty(district))
q = q.Where(p => p.District.Contains(district));
if (!string.IsNullOrEmpty(zip))
q = q.Where(p => p.Zip == zip);
if (!string.IsNullOrEmpty(region))
q = q.Where(p => p.Region.Contains(region));
if (!string.IsNullOrEmpty(country))
q = q.Where(p => p.Country == country);
return q;
}
(Actually, this query is a bit more compicated.) This works well building an SQL query with some LIKE.
Now I would like to use the same query for an array of MyType:
MyType[] SelectFromResult(MyType[] loc, string city, string district, string region, string country, string zip)
{
var q = BuildQuery(loc, city, district, region, country, zip);
return q.ToArray();
}
Of coarse this does not compile because MyType[] is an IEnumerable<MyType>, not an IQueryable<MyType>. Changing the type of the first argument in BuildQuery to IEnumerable<MyType>, compiles and works for arrays but won't build the SQL query.
I guess I could make BuildQuery a generic method, but how? Any ideas?
.AsQueryable()does that work?