Reputation: 21
I hava table with multiple vehicle columns
My corresponding SQL Query is
sQuery = "Select * from Vehicle where " + variant + "='Y'";
How can I write the same query in LINQ?
Upvotes: 1
Views: 1051
Reputation: 21
This may also be another approach:
PropertyInfo pi = typeof(Vehicles).GetProperty(vehVariant);
var services = context.Vehicles.ToList();
services = services.Where(item => pi.GetValue(item).ToString().Trim() == "Y").ToList();
Happy Coding.
Upvotes: 0
Reputation: 49600
Try this:
Vehiclelist.Where(q => q.Trucks=="Y" || q.Cars=="Y" || q.Utility=="Y");
Upvotes: 0
Reputation: 24
using lambda expression :
VehicleDatatable.AsEnumerable().Where(q=>q.Trucks=="Y" || q.Cars=="Y" || q.Utility=="Y");
Another way
(from d in VehicleDatatable.AsEnumerable() where string.compare(d["Trucks"],"Y")==0 select d)
Upvotes: 0
Reputation: 24913
Build your query:
var query = Vehiclelist;
if (column == "Trucks")
{
query = query.Where(q => q.Trucks=="Y");
}
else if (column == "Cars")
{
query = query.Where(q => q.Cars=="Y");
}
else if (column == "Utility")
{
query = query.Where(q => q.Utility=="Y");
}
This approach is more maintainable, more testable. You have strong-typed expressions and transparent filters.
Upvotes: 2
Reputation: 16150
You can build lambda expression dynamically by using System.Linq.Expression
namespace and pass it to Where
method.
For example:
public IQueryable<Vehicle> GetAccounts(string variant)
{
// Build equivalent lambda to 'param => param.{variant} == "Y"'
// This is lambda parameter
var param = Expression.Parameter(typeof(Vehicle));
// This is lambda body (comparison)
var body = Expression.Equal(
// Access property {variant} of param
Expression.Property(param, typeof(Vehicle).GetProperty(variant)),
// Constant value "Y"
Expression.Constant("Y")
);
// Build lambda using param and body defined above
var lambda = Expression.Lambda<Func<Vehicle, bool>>(body, param);
// Use created lambda in query
return VehicleDatatable.Where(lambda);
}
Another idea is to convert query a bit. You can realize same work using following query:
sQuery = "Select * from Vehicle where (Tracks+Cars+Utility) LIKE '" + value + "'";
Where value
is 'Y__' or 'Y' or '__Y' depending on which vehicle type you want to query. It's definitely not most effective, but that is pretty easy to convert to linq.
Upvotes: 2