How to create a dynamic selection expression in LINQ?

What I currently have looks something like this:

if(userLikesBananas)
{
    return from fruit in basket
           select new Fruit
           {
               AteBanana = Bowl.Any(b => b.OwnedBy == user && b.Contains(fruit) && fruit.Type == FruitType.Banana),
               ...
               ...
               //lots of properties
               ...
           }
}
else
{
    return from fruit in basket
           select new Fruit
           {
               AteBanana = Bowl.Any(b => b.Contains(fruit)),
               ...
               ...
               //lots of properties
               ...
           }
}

True, the example makes absolutely no sense, but the principle is that I want to change the conditions for choosing properties based on arbitrary criteria. Right now, select commands are repeating.

Now the time has come when I need to add criteria depending on the anoter. I do not want to have 4 different cases when the conditions of the property are slightly different.

What I want to do is something like this:

Func<Fruit, bool> fruitFunc = f => false;

if(userLikesBananas)
{
    fruitFunc = f => Bowl.Any(b => b.OwnedBy == user && b.Contains(f) && f.Type == FruitType.Banana);
}
else
{
    fruitFunc = f => Bowl.Any(b => b.Contains(f));
}

return from fruit in basket
       select new Fruit
       {
           AteBanana = fruitFunc(fruit)
           ...
           ...
           //lots of properties
           ...
       };

The problem is that the expression cannot be converted to sql, because it contains a dynamic call. I tried to wrap Funcin Expression, but the same problem occurs.

So the question is, how can I avoid copying and pasting?

+3
2

... , , : -)

Linq - , (x.Name, x.Surname ..)

(litle noob-like) ( ):

  • enum , .

    public enum MyAtrs {ID, FirstName, Surname}

  • Dictionary<MyAtrs,bool> ( ) ( true, )

    Dic = (); Dic.Add(MyAtrs.ID, ); Dic.Add(MyAtrs.Firstname, ); Dic.Add(MyAtrs.Surname, );

  • :

    var query = DBContext.MyDBTable.Where(). (e = > new { ID = Dic [MyAtrs.ID]? e.dbID: 0, = Dic [MyAtrs.Firstname]? e.dbFirstname: , = Dic [MyAtrs.Surname]? e.dbSurname: , });

SQL Select 3 , ( ...). SQL Server 3 , ( ) (- {ID = 123, Firstname =, Surname = "Jobs" }). , , "" :)

+3

Func - ( , - ):

fruitFunc = f => Bowl.Any(b => ((f.Type == FruitType.Banana && b.OwnedBy == user && userLikesBananas) || !userLikesBananas) && b.Contains(f));

, , ( 2). - , ...

...

0

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


All Articles