Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic "Not" by parameter in LINQ (Or any other code for that matter)

Okay,

This may be really simple or it may not even be possible, or I am just having a brain freeze :)

Here is an example of what I am trying to do:

public void SomeMethod(bool include)
        {
            using (AccountDataContext db = AccountContextFactory.CreateContext())
            {
                if (include)
                {
                    var query = from a in db.FundingTypes where a.FundingTypeId == 1 select a;
                }
                else
                {
                    var query = from a in db.FundingTypes where a.FundingTypeId != 1 select a;
                }
            }
        }

I would like to dynamically change the != and = without having to write an entire new query. The query that I am using in real life is very large and I don't like code duplication.

Thought or Ideas?

Thanks

like image 612
CodeLikeBeaker Avatar asked Jan 30 '26 00:01

CodeLikeBeaker


1 Answers

That seems perfectly straightforward.

var predicate = include ? 
  (Func<int, bool>) x=>x == 1 : 
  (Func<int, bool>) x=>x != 1 ;
var query = from a in db.FundingTypes where predicate(a.FundingTypeId) select a;
like image 61
Eric Lippert Avatar answered Jan 31 '26 15:01

Eric Lippert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!