How to reorganize several similar Linq queries?

Suppose I have the following two Linq queries that I want to reorganize:

var someValue1 = 0;
var someValue2= 0;
var query1 = db.TableAs.Where( a => a.TableBs.Count() > someValue1 )
                  .Take( 10 );
var query2 = db.TableAs.Where( a => a.TableBs.First().item1 == someValue2)
                  .Take( 10 );

Note that only the Where parameter is changed. Is there any way to put a request inside a method and pass the Where parameter as an argument?

+2
source share
4 answers

Out of the mouse there. The where parameter is a simple type closure Func<T, bool>(where T is the type of your database items โ€” I donโ€™t know them from your code), and you can wrap it in a (anonymous) function.

Func<Func<T, bool>, IEnumerable<T>> MakeQuery = (Func<T, bool> whereParam) => db.TableAs.Where(whereParam).Take(10);

Use it like this:

var query1 = MakeQuery(a => a.TableBS.Count() > someValue1);
+2
source

You can use Predicate<T>.

public IQueryable<TableA> Helper(Predicate<TableA> predicate)
{
    return db.TableAs.Where(predicate).Take(10);
}

Just call it that.

var query1 = Helper(a => a.TableBs.Count() > someValue1);
var query2 = Helper(a => a.TableBs.First().item1 == someValue2);

, Helper.

+2

, - lamba Func<TSource, bool>

Func<Person, bool> c1 = p => p.LastName == "1";
Persons.Where(c1);
Func<Person, bool> c2 = p => p.FirstName == "2";
Persons.Where(c2)
+1

, :

T MyQuery(U db, Func<TSource, bool> pred) {
  return db.TableAs.Where( pred )
                  .Take( 10 );
}

T U - , .

+1

Source: https://habr.com/ru/post/1708375/


All Articles