Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 623
Patrick Avatar asked Sep 12 '13 10:09

Patrick


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is C and C++ meaning?

C is a function driven language because C is a procedural programming language. C++ is an object driven language because it is an object oriented programming. Function and operator overloading is not supported in C. Function and operator overloading is supported by C++. C is a function-driven language.


2 Answers

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();
    }
like image 82
Burk Avatar answered Sep 17 '22 21:09

Burk


A nice way is to use Dynamic Linq

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

Something like:

var s1 = (from c in db.Components
    where(column + "=" + value)
    select new {c.id, **column**});
like image 35
Dave Bish Avatar answered Sep 17 '22 21:09

Dave Bish