Note that there are some explanatory texts on larger screens.

plurals
  1. PODynamic query in LINQ
    primarykey
    data
    text
    <p>How do I write a dynamic query for Linq, if I have say Customer class which holds the fields:</p> <pre><code>string name string address int phoneno </code></pre> <p>I have to query based on information given similar to</p> <pre><code>query = string.Empty; if(!string.IsNullorEmpty(name)) { query += "@name = name"; } if(!string.IsNullorEmpty(address)) { query += "@address = address"; } if(!string.IsNullorEmpty(phoneno)) { query += "@phoneno = phoneno"; } var result = from condition in customer where(query) select condition; </code></pre> <p><strong>Edit #1:</strong> </p> <p>the items are changeable at run time like</p> <pre><code>private Customer[] GetCustomers(Dictionary&lt;string,string&gt; attributes) { here the attribute may be, name alone, or name and address, or name address and phoneno foreach(string field in attributes.key) { query += field == attributes[key]; } Customers[] =ExecuteQuery(query); } </code></pre> <p>Is this kind of query supported by LINQ?</p> <p><strong>Edit #2:</strong></p> <p>Hi Mouk,<br> As I am new to C#, I am still struggling, this is not working for me.</p> <pre><code>var query = _ConfigFile.ConnectionMasterSection; for(int i = 0; i &lt; filter.count; i++) { query = result.Where(p =&gt; typeof(ConnectionMaster).GetProperty(filter[i].Attribute).Name == filter[i].Value); } </code></pre> <p>This yeilds Empty, where as i used this</p> <pre><code>var query = _ConfigFile.ConnectionMasterSection; //Hard coded res.Where(q =&gt; q.category == filter[0].Value); </code></pre> <p>And it worked as I expected.</p> <p>Hi Bryan Watts,<br> I tried your code also and I getting this error: "Lambda Parameter not in scope".</p> <pre><code>for(int i = 0; i &lt; filter.count; i++) { Field item = filter[i]; MemberExpression param = Expression.MakeMemberAccess(Expression.Parameter(typeof(Connection), "p"), typeof(Connection).GetProperty(item.Attribute)); MemberExpression constant = Expression.MakeMemberAccess(Expression.Constant(item), typeof(Field).GetProperty("Value")); } try { var myquery = Queryable.Where(coll, Expression.Lambda&lt;Func&lt;Connection, bool&gt;&gt;( Expression.Equal(param, constant), Expression.Parameter(typeof(Connection),"p"))); } </code></pre> <p>What is the mistake here?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload