简体   繁体   中英

LINQ for dynamic columns in a table in c#

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?

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.

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.

尝试这个:

Vehiclelist.Where(q => q.Trucks=="Y" || q.Cars=="Y" || q.Utility=="Y");

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM