Search code examples
c#linqentity-framework

C# Linq Column Name as variable


I have a table where I want to make a query on variable columns. Like:

private void query(string column, string value) {

    using (var db = new myDB()) {

        var s1 = (from c in db.Components
                  where (**column** == **value**)
                  select new {c.id, **column**});
    }
}

lets say I want to look for a supplier then it would be like:

var s1 = (from c in db.Components
          where (c.supplier == "abc")
          select new {c.id, c.supplier});

is there a way to pass the column name as variable?


Solution

  • This example can be useful i guess.

     void BindGridTypeSafe()
        {
            NorthwindDataContext northwind = new NorthwindDataContext();
    
            var query = from p in northwind.Products
                        where p.CategoryID == 3 && p.UnitPrice > 3
                        orderby p.SupplierID
                        select p;
    
            GridView1.DataSource = query;
            GridView1.DataBind();
        }
    
        void BindGridDynamic()
        {
            NorthwindDataContext northwind = new NorthwindDataContext();
    
            var query = northwind.Products
                                 .Where("CategoryID = 3 AND UnitPrice > 3")
                                 .OrderBy("SupplierID");
    
            GridView1.DataSource = query;
            GridView1.DataBind();
        }