Add dynamically predicate to expression without PredicateBuilder









up vote
2
down vote

favorite












I use linqToEntities and would like to add OR condition dynamically.



I know that there is a great library PredicateBuilder by brother Albahari and it can solve my task, but I cannot use it.



My conditions looks like this:



IEnumerable<Condition> conditions = new List<Condition>()

new Condition()IdReference = 1, TableName = "Table1" ,
new Condition()IdReference = 2, TableName = "Table2" ,
new Condition()IdReference = 3, TableName = "Table3" ,
// and so on
;


What I have is:



var histories = db.History as IQueryable<History>;
foreach (var cond in conditions)



However, I do not know in advance how many conditions would be.
How is it possible to add OR conditions dynamically from IEnumerable<Condition>?










share|improve this question



















  • 1




    If you don't have too many combinations, just use some conditions: if(thisIsTheCase) histories = histories.Where(// put your conditions else if(another Case) histories = histories.Where(// put your conditions add more if else until you have covered all cases. You can also do it by creating dynamic expressions but it will not be easy because you will need to combine the expressions.
    – CodingYoshi
    Nov 11 at 14:21






  • 2




    Why can you not use PredicateBuilder?
    – CodingYoshi
    Nov 11 at 14:48










  • @CodingYoshi as my code will not be passed a code review.
    – StepUp
    Nov 11 at 16:23














up vote
2
down vote

favorite












I use linqToEntities and would like to add OR condition dynamically.



I know that there is a great library PredicateBuilder by brother Albahari and it can solve my task, but I cannot use it.



My conditions looks like this:



IEnumerable<Condition> conditions = new List<Condition>()

new Condition()IdReference = 1, TableName = "Table1" ,
new Condition()IdReference = 2, TableName = "Table2" ,
new Condition()IdReference = 3, TableName = "Table3" ,
// and so on
;


What I have is:



var histories = db.History as IQueryable<History>;
foreach (var cond in conditions)



However, I do not know in advance how many conditions would be.
How is it possible to add OR conditions dynamically from IEnumerable<Condition>?










share|improve this question



















  • 1




    If you don't have too many combinations, just use some conditions: if(thisIsTheCase) histories = histories.Where(// put your conditions else if(another Case) histories = histories.Where(// put your conditions add more if else until you have covered all cases. You can also do it by creating dynamic expressions but it will not be easy because you will need to combine the expressions.
    – CodingYoshi
    Nov 11 at 14:21






  • 2




    Why can you not use PredicateBuilder?
    – CodingYoshi
    Nov 11 at 14:48










  • @CodingYoshi as my code will not be passed a code review.
    – StepUp
    Nov 11 at 16:23












up vote
2
down vote

favorite









up vote
2
down vote

favorite











I use linqToEntities and would like to add OR condition dynamically.



I know that there is a great library PredicateBuilder by brother Albahari and it can solve my task, but I cannot use it.



My conditions looks like this:



IEnumerable<Condition> conditions = new List<Condition>()

new Condition()IdReference = 1, TableName = "Table1" ,
new Condition()IdReference = 2, TableName = "Table2" ,
new Condition()IdReference = 3, TableName = "Table3" ,
// and so on
;


What I have is:



var histories = db.History as IQueryable<History>;
foreach (var cond in conditions)



However, I do not know in advance how many conditions would be.
How is it possible to add OR conditions dynamically from IEnumerable<Condition>?










share|improve this question















I use linqToEntities and would like to add OR condition dynamically.



I know that there is a great library PredicateBuilder by brother Albahari and it can solve my task, but I cannot use it.



My conditions looks like this:



IEnumerable<Condition> conditions = new List<Condition>()

new Condition()IdReference = 1, TableName = "Table1" ,
new Condition()IdReference = 2, TableName = "Table2" ,
new Condition()IdReference = 3, TableName = "Table3" ,
// and so on
;


What I have is:



var histories = db.History as IQueryable<History>;
foreach (var cond in conditions)



However, I do not know in advance how many conditions would be.
How is it possible to add OR conditions dynamically from IEnumerable<Condition>?







c# entity-framework linq entity-framework-6 linq-to-entities






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 at 13:37

























asked Nov 11 at 12:53









StepUp

6,84774473




6,84774473







  • 1




    If you don't have too many combinations, just use some conditions: if(thisIsTheCase) histories = histories.Where(// put your conditions else if(another Case) histories = histories.Where(// put your conditions add more if else until you have covered all cases. You can also do it by creating dynamic expressions but it will not be easy because you will need to combine the expressions.
    – CodingYoshi
    Nov 11 at 14:21






  • 2




    Why can you not use PredicateBuilder?
    – CodingYoshi
    Nov 11 at 14:48










  • @CodingYoshi as my code will not be passed a code review.
    – StepUp
    Nov 11 at 16:23












  • 1




    If you don't have too many combinations, just use some conditions: if(thisIsTheCase) histories = histories.Where(// put your conditions else if(another Case) histories = histories.Where(// put your conditions add more if else until you have covered all cases. You can also do it by creating dynamic expressions but it will not be easy because you will need to combine the expressions.
    – CodingYoshi
    Nov 11 at 14:21






  • 2




    Why can you not use PredicateBuilder?
    – CodingYoshi
    Nov 11 at 14:48










  • @CodingYoshi as my code will not be passed a code review.
    – StepUp
    Nov 11 at 16:23







1




1




If you don't have too many combinations, just use some conditions: if(thisIsTheCase) histories = histories.Where(// put your conditions else if(another Case) histories = histories.Where(// put your conditions add more if else until you have covered all cases. You can also do it by creating dynamic expressions but it will not be easy because you will need to combine the expressions.
– CodingYoshi
Nov 11 at 14:21




If you don't have too many combinations, just use some conditions: if(thisIsTheCase) histories = histories.Where(// put your conditions else if(another Case) histories = histories.Where(// put your conditions add more if else until you have covered all cases. You can also do it by creating dynamic expressions but it will not be easy because you will need to combine the expressions.
– CodingYoshi
Nov 11 at 14:21




2




2




Why can you not use PredicateBuilder?
– CodingYoshi
Nov 11 at 14:48




Why can you not use PredicateBuilder?
– CodingYoshi
Nov 11 at 14:48












@CodingYoshi as my code will not be passed a code review.
– StepUp
Nov 11 at 16:23




@CodingYoshi as my code will not be passed a code review.
– StepUp
Nov 11 at 16:23












2 Answers
2






active

oldest

votes

















up vote
2
down vote



accepted










Not sure what's the problem with using predicate builder - it doesn't have to be LINQ Kit package, the so called predicate builder is usually a single static class with 2 extension methods - like Universal Predicate Builder or my own PredicateUtils from Establish a link between two lists in linq to entities where clause and similar.



Anyway, once you want it, of course it could be built using just plain Expression class static methods.



Add the following in order to eliminate the need of writing Expression. before each call:



using static System.Linq.Expressions.Expression;


and then use something like this:



if (conditions.Any())

var parameter = Parameter(typeof(History));
var body = conditions
.Select(condition => Expression.Constant(condition))
.Select(condition => Expression.AndAlso(
Expression.Equal(
Expression.PropertyOrField(parameter, nameof(History.IdReference)),
Expression.Convert(
Expression.PropertyOrField(condition, nameof(Condition.IdReference))
, Expression.PropertyOrField(parameter, nameof(History.IdReference)).Type)
),
Expression.Equal(
Expression.PropertyOrField(parameter, nameof(History.TableName)),
Expression.Convert(
Expression.PropertyOrField(condition, nameof(Condition.TableName))
, Expression.PropertyOrField(parameter, nameof(History.TableName)).Type)
)
))
.Aggregate(Expression.OrElse);
var predicate = Lambda<Func<History, bool>>(body, parameter);
histories = histories.Where(predicate);






share|improve this answer






















  • man, you are awesome! master! Thank you very much!
    – StepUp
    Nov 11 at 18:39


















up vote
0
down vote













As I understand you mean



var histories = db.History as IQueryable<History>;
foreach (var cond in conditions)

//What code should be here to be translated into:

histories = histories
.Where(h => h.IdReference == cond.IdReference &&
h.TableName ==cond.TableName );







share|improve this answer
















  • 1




    He does not know the conditions until runtime. This will work if they were known.
    – CodingYoshi
    Nov 11 at 14:23










  • As I understood he dose not know how many conditions in History list but he have fixed conditions in conditionList so looping in conditionList and comparing !! As I thought :)
    – Hitham Yosri
    Nov 11 at 14:52










  • Chaining Wheres is the equivilent of and not or.
    – David Browne - Microsoft
    Nov 11 at 15:56










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53248938%2fadd-dynamically-predicate-to-expression-without-predicatebuilder%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
2
down vote



accepted










Not sure what's the problem with using predicate builder - it doesn't have to be LINQ Kit package, the so called predicate builder is usually a single static class with 2 extension methods - like Universal Predicate Builder or my own PredicateUtils from Establish a link between two lists in linq to entities where clause and similar.



Anyway, once you want it, of course it could be built using just plain Expression class static methods.



Add the following in order to eliminate the need of writing Expression. before each call:



using static System.Linq.Expressions.Expression;


and then use something like this:



if (conditions.Any())

var parameter = Parameter(typeof(History));
var body = conditions
.Select(condition => Expression.Constant(condition))
.Select(condition => Expression.AndAlso(
Expression.Equal(
Expression.PropertyOrField(parameter, nameof(History.IdReference)),
Expression.Convert(
Expression.PropertyOrField(condition, nameof(Condition.IdReference))
, Expression.PropertyOrField(parameter, nameof(History.IdReference)).Type)
),
Expression.Equal(
Expression.PropertyOrField(parameter, nameof(History.TableName)),
Expression.Convert(
Expression.PropertyOrField(condition, nameof(Condition.TableName))
, Expression.PropertyOrField(parameter, nameof(History.TableName)).Type)
)
))
.Aggregate(Expression.OrElse);
var predicate = Lambda<Func<History, bool>>(body, parameter);
histories = histories.Where(predicate);






share|improve this answer






















  • man, you are awesome! master! Thank you very much!
    – StepUp
    Nov 11 at 18:39















up vote
2
down vote



accepted










Not sure what's the problem with using predicate builder - it doesn't have to be LINQ Kit package, the so called predicate builder is usually a single static class with 2 extension methods - like Universal Predicate Builder or my own PredicateUtils from Establish a link between two lists in linq to entities where clause and similar.



Anyway, once you want it, of course it could be built using just plain Expression class static methods.



Add the following in order to eliminate the need of writing Expression. before each call:



using static System.Linq.Expressions.Expression;


and then use something like this:



if (conditions.Any())

var parameter = Parameter(typeof(History));
var body = conditions
.Select(condition => Expression.Constant(condition))
.Select(condition => Expression.AndAlso(
Expression.Equal(
Expression.PropertyOrField(parameter, nameof(History.IdReference)),
Expression.Convert(
Expression.PropertyOrField(condition, nameof(Condition.IdReference))
, Expression.PropertyOrField(parameter, nameof(History.IdReference)).Type)
),
Expression.Equal(
Expression.PropertyOrField(parameter, nameof(History.TableName)),
Expression.Convert(
Expression.PropertyOrField(condition, nameof(Condition.TableName))
, Expression.PropertyOrField(parameter, nameof(History.TableName)).Type)
)
))
.Aggregate(Expression.OrElse);
var predicate = Lambda<Func<History, bool>>(body, parameter);
histories = histories.Where(predicate);






share|improve this answer






















  • man, you are awesome! master! Thank you very much!
    – StepUp
    Nov 11 at 18:39













up vote
2
down vote



accepted







up vote
2
down vote



accepted






Not sure what's the problem with using predicate builder - it doesn't have to be LINQ Kit package, the so called predicate builder is usually a single static class with 2 extension methods - like Universal Predicate Builder or my own PredicateUtils from Establish a link between two lists in linq to entities where clause and similar.



Anyway, once you want it, of course it could be built using just plain Expression class static methods.



Add the following in order to eliminate the need of writing Expression. before each call:



using static System.Linq.Expressions.Expression;


and then use something like this:



if (conditions.Any())

var parameter = Parameter(typeof(History));
var body = conditions
.Select(condition => Expression.Constant(condition))
.Select(condition => Expression.AndAlso(
Expression.Equal(
Expression.PropertyOrField(parameter, nameof(History.IdReference)),
Expression.Convert(
Expression.PropertyOrField(condition, nameof(Condition.IdReference))
, Expression.PropertyOrField(parameter, nameof(History.IdReference)).Type)
),
Expression.Equal(
Expression.PropertyOrField(parameter, nameof(History.TableName)),
Expression.Convert(
Expression.PropertyOrField(condition, nameof(Condition.TableName))
, Expression.PropertyOrField(parameter, nameof(History.TableName)).Type)
)
))
.Aggregate(Expression.OrElse);
var predicate = Lambda<Func<History, bool>>(body, parameter);
histories = histories.Where(predicate);






share|improve this answer














Not sure what's the problem with using predicate builder - it doesn't have to be LINQ Kit package, the so called predicate builder is usually a single static class with 2 extension methods - like Universal Predicate Builder or my own PredicateUtils from Establish a link between two lists in linq to entities where clause and similar.



Anyway, once you want it, of course it could be built using just plain Expression class static methods.



Add the following in order to eliminate the need of writing Expression. before each call:



using static System.Linq.Expressions.Expression;


and then use something like this:



if (conditions.Any())

var parameter = Parameter(typeof(History));
var body = conditions
.Select(condition => Expression.Constant(condition))
.Select(condition => Expression.AndAlso(
Expression.Equal(
Expression.PropertyOrField(parameter, nameof(History.IdReference)),
Expression.Convert(
Expression.PropertyOrField(condition, nameof(Condition.IdReference))
, Expression.PropertyOrField(parameter, nameof(History.IdReference)).Type)
),
Expression.Equal(
Expression.PropertyOrField(parameter, nameof(History.TableName)),
Expression.Convert(
Expression.PropertyOrField(condition, nameof(Condition.TableName))
, Expression.PropertyOrField(parameter, nameof(History.TableName)).Type)
)
))
.Aggregate(Expression.OrElse);
var predicate = Lambda<Func<History, bool>>(body, parameter);
histories = histories.Where(predicate);







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 11 at 18:39









StepUp

6,84774473




6,84774473










answered Nov 11 at 18:02









Ivan Stoev

97.7k767121




97.7k767121











  • man, you are awesome! master! Thank you very much!
    – StepUp
    Nov 11 at 18:39

















  • man, you are awesome! master! Thank you very much!
    – StepUp
    Nov 11 at 18:39
















man, you are awesome! master! Thank you very much!
– StepUp
Nov 11 at 18:39





man, you are awesome! master! Thank you very much!
– StepUp
Nov 11 at 18:39













up vote
0
down vote













As I understand you mean



var histories = db.History as IQueryable<History>;
foreach (var cond in conditions)

//What code should be here to be translated into:

histories = histories
.Where(h => h.IdReference == cond.IdReference &&
h.TableName ==cond.TableName );







share|improve this answer
















  • 1




    He does not know the conditions until runtime. This will work if they were known.
    – CodingYoshi
    Nov 11 at 14:23










  • As I understood he dose not know how many conditions in History list but he have fixed conditions in conditionList so looping in conditionList and comparing !! As I thought :)
    – Hitham Yosri
    Nov 11 at 14:52










  • Chaining Wheres is the equivilent of and not or.
    – David Browne - Microsoft
    Nov 11 at 15:56














up vote
0
down vote













As I understand you mean



var histories = db.History as IQueryable<History>;
foreach (var cond in conditions)

//What code should be here to be translated into:

histories = histories
.Where(h => h.IdReference == cond.IdReference &&
h.TableName ==cond.TableName );







share|improve this answer
















  • 1




    He does not know the conditions until runtime. This will work if they were known.
    – CodingYoshi
    Nov 11 at 14:23










  • As I understood he dose not know how many conditions in History list but he have fixed conditions in conditionList so looping in conditionList and comparing !! As I thought :)
    – Hitham Yosri
    Nov 11 at 14:52










  • Chaining Wheres is the equivilent of and not or.
    – David Browne - Microsoft
    Nov 11 at 15:56












up vote
0
down vote










up vote
0
down vote









As I understand you mean



var histories = db.History as IQueryable<History>;
foreach (var cond in conditions)

//What code should be here to be translated into:

histories = histories
.Where(h => h.IdReference == cond.IdReference &&
h.TableName ==cond.TableName );







share|improve this answer












As I understand you mean



var histories = db.History as IQueryable<History>;
foreach (var cond in conditions)

//What code should be here to be translated into:

histories = histories
.Where(h => h.IdReference == cond.IdReference &&
h.TableName ==cond.TableName );








share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 11 at 13:58









Hitham Yosri

11




11







  • 1




    He does not know the conditions until runtime. This will work if they were known.
    – CodingYoshi
    Nov 11 at 14:23










  • As I understood he dose not know how many conditions in History list but he have fixed conditions in conditionList so looping in conditionList and comparing !! As I thought :)
    – Hitham Yosri
    Nov 11 at 14:52










  • Chaining Wheres is the equivilent of and not or.
    – David Browne - Microsoft
    Nov 11 at 15:56












  • 1




    He does not know the conditions until runtime. This will work if they were known.
    – CodingYoshi
    Nov 11 at 14:23










  • As I understood he dose not know how many conditions in History list but he have fixed conditions in conditionList so looping in conditionList and comparing !! As I thought :)
    – Hitham Yosri
    Nov 11 at 14:52










  • Chaining Wheres is the equivilent of and not or.
    – David Browne - Microsoft
    Nov 11 at 15:56







1




1




He does not know the conditions until runtime. This will work if they were known.
– CodingYoshi
Nov 11 at 14:23




He does not know the conditions until runtime. This will work if they were known.
– CodingYoshi
Nov 11 at 14:23












As I understood he dose not know how many conditions in History list but he have fixed conditions in conditionList so looping in conditionList and comparing !! As I thought :)
– Hitham Yosri
Nov 11 at 14:52




As I understood he dose not know how many conditions in History list but he have fixed conditions in conditionList so looping in conditionList and comparing !! As I thought :)
– Hitham Yosri
Nov 11 at 14:52












Chaining Wheres is the equivilent of and not or.
– David Browne - Microsoft
Nov 11 at 15:56




Chaining Wheres is the equivilent of and not or.
– David Browne - Microsoft
Nov 11 at 15:56

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53248938%2fadd-dynamically-predicate-to-expression-without-predicatebuilder%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

Barbados

How to read a connectionString WITH PROVIDER in .NET Core?

Node.js Script on GitHub Pages or Amazon S3