Note that there are some explanatory texts on larger screens.

plurals
  1. POGeneric LINQ query predicate?
    primarykey
    data
    text
    <p>Not sure if this is possible or if I'm expressing correctly what I'm looking for, but I have the following piece of code in my library repeatedly and would like to practice some DRY. I have set of SQL Server tables that I'm querying based on a simple user-supplied search field ala Google. I'm using LINQ to compose the final query based on what's in the search string. I'm looking for a way to use generics and passed in lambda functions to create a reusable routine out of this: </p> <pre><code>string[] arrayOfQueryTerms = getsTheArray(); var somequery = from q in dataContext.MyTable select q; if (arrayOfQueryTerms.Length == 1) { somequery = somequery.Where&lt;MyTableEntity&gt;( e =&gt; e.FieldName.StartsWith(arrayOfQueryTerms[0])); } else { foreach(string queryTerm in arrayOfQueryTerms) { if (!String.IsNullOrEmpty(queryTerm)) { somequery = somequery .Where&lt;MyTableEntity&gt;( e =&gt; e.FieldName.Contains(queryTerm)); } } } </code></pre> <p>I was hoping to create a generic method with signature that looks something like:</p> <pre><code>private IQueryable&lt;T&gt; getQuery( T MyTableEntity, string[] arrayOfQueryTerms, Func&lt;T, bool&gt; predicate) </code></pre> <p>I'm using the same search strategy across all my tables, so the only thing that really differs from usage to usage is the MyTable &amp; MyTableEntity searched and the FieldName searched. Does this make sense? Is there a way with LINQ to dynamically pass in the name of the field to query in the where clause? Or can I pass in this as a predicate lambda?</p> <pre><code>e =&gt; e.FieldName.Contains(queryTerm) </code></pre> <p>I realize there a million and a half ways to do this in SQL, probably easier, but I'd love to keep everything in the LINQ family for this one. Also, I feel that generics should be handy for a problem like this. Any ideas?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    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