Dynamic column name in LAMBDA C#

Last Reply 11 days ago By dharmendr

Posted 12 days ago

Hi,

I need to provide the column name dynamically

var columname = "customername";

var customers = ctx.Customers.where(c=>c.state == 1).select(columname).tolist();

You are viewing reply posted by: dharmendr 11 days ago.
Posted 11 days ago

HiRockstar8,

Use query like below.

NorthwindEntities entity = new NorthwindEntities();
var customers = entity.Customers.ToList();
var result = new List<Customer>();
var data = new Customer();
var type = data.GetType();
var columName = "CustomerID";

for (var i = 0; i < customers.Count; i++)
{
    foreach (var property in data.GetType().GetProperties())
    {
        if (property.Name == columName)
        {
            type.GetProperties().FirstOrDefault(n => n.Name == property.Name)
                .SetValue(data, GetPropValue(customers[i], property.Name), null);
            result.Add(data);
        }
    }
}

GetPropValue

public static object GetPropValue(object src, string propName)
{
    return src.GetType().GetProperty(propName).GetValue(src, null);
}