Note that there are some explanatory texts on larger screens.

plurals
  1. POGeneric List of OrderBy Lambda
    primarykey
    data
    text
    <p>I am trying to build a generic query mechanism to access my repository. I wish to use Lambda expressions to filter and sort the query. I am struggling to find a way to pass a list of generic Lambda expressions in, specifically for the order-by, and would appreciate help in doing so.</p> <p>EDIT: 2 requirements I am trying to meet is, not expose IQueryable beyond the repository, but still be able to carry out some filtering and sorting at database level.</p> <p>To better illustrate this let me show you the code</p> <pre><code>public class Query&lt;T&gt; { public class OrderBy&lt;T&gt; { public Expression&lt;Func&lt;T, **int**&gt;&gt; Clause { set; get; } // Order By clause public bool Descending = true; } public Expression&lt;Func&lt;T, bool&gt;&gt; Where { set; get; } // Where clause public IList&lt;OrderBy&lt;T&gt;&gt; OrderBys { set; get; } // Where clause public Query() { OrderBys = new List&lt;OrderBy&lt;T&gt;&gt;(); } } public IEnumerable&lt;Person&gt; FindBy(Query&lt;Person&gt; query) { IQueryable&lt;Person&gt; Temp = GetObjectSet(); if (query.Where != null) Temp = Temp.Where(query.Where); foreach (var OrderByThis in query.OrderBys) { if (OrderByThis.Descending) Temp = Temp.OrderByDescending(OrderByThis.Clause); else Temp = Temp.OrderBy(OrderByThis.Clause); } return Temp.ToList&lt;Person&gt;(); } </code></pre> <p>This is all very nice, BUT Expression&lt; Func&lt; T, <strong>int</strong>>> is not generic. I need to be able to do something like:</p> <pre><code>Query&lt;Person&gt; query = new Query&lt;Person&gt;(); Query&lt;Person&gt;.OrderBy&lt;Person&gt; clause1 = new Query&lt;Person&gt;.OrderBy&lt;Person&gt;(); clause1.Clause = m =&gt; m.Username; Query&lt;Person&gt;.OrderBy&lt;Person&gt; clause2 = new Query&lt;Person&gt;.OrderBy&lt;Person&gt;(); clause2.Clause = m =&gt; m.DateOfBirth; query.OrderBys.Add(clause1); query.OrderBys.Add(clause2); </code></pre> <p>i.e. adding a number of different fields of different types.</p> <p>I imagine there must be a way to store these as generic Lambda functions, and then in the repository convert then to the strongly typed Lambda function it needs.</p> <p>How can I do this?</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