1

I hava table with multiple vehicle columns enter image description here

My corresponding SQL Query is

sQuery = "Select * from Vehicle where " + variant + "='Y'";

How can I write the same query in LINQ?

  • 1
    Possible duplicate of [Dynamic where condition in LINQ](http://stackoverflow.com/questions/5674639/dynamic-where-condition-in-linq) – Circle Hsiao Dec 30 '16 at 06:35

5 Answers5

2

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.

Krzysztof
  • 15,900
  • 2
  • 46
  • 76
2

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.

Backs
  • 24,430
  • 5
  • 58
  • 85
0

Try this:

Vehiclelist.Where(q => q.Trucks=="Y" || q.Cars=="Y" || q.Utility=="Y");
Backs
  • 24,430
  • 5
  • 58
  • 85
GorvGoyl
  • 42,508
  • 29
  • 229
  • 225
0

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)
0

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.