HamedStack.PredicateBuilder
is a powerful, fluent, and expressive C# library to dynamically build LINQ expressions (predicates) for filtering collections, querying databases, and more.
Perfect for scenarios like:
- Complex search filters
- Dynamic API queries
- Advanced logical expression combinations
Just add a reference to the compiled library, or include the source in your project.
- Predicate: A function
T => bool
used for filtering. - Builder: Use fluent methods to dynamically build predicates using logical operations.
- Composition: Use
And
,Or
,Xor
,Nor
,Nand
,Xnor
, and their negations.
var builder = new PredicateQueryBuilder<Person>();
builder.AndWhere(p => p.Age > 18)
.OrWhere(p => p.Name.StartsWith("A"));
var predicate = builder.Build();
var result = people.Where(predicate.Compile()).ToList();
Add predicate using logical AND.
builder.Where(p => p.Age > 18);
Add using logical OR.
builder.OrWhere(p => p.Name.StartsWith("A"));
Add negated predicates.
builder.AndWhereNot(p => p.IsActive);
Nest logic inside a group. Useful for grouped conditions:
builder.OrGroup(g => {
g.AndWhere(p => p.Age > 30)
.AndWhere(p => p.City == "Paris");
});
builder.OrGroupNot(g => {
g.AndWhere(p => p.IsActive);
});
Method | Description |
---|---|
And |
Logical AND |
Or |
Logical OR |
Not |
Logical NOT |
Xor |
Exclusive OR |
Xnor |
Exclusive NOR |
Nand |
NOT AND |
Nor |
NOT OR |
builder.XorWhere(p => p.IsMale);
Grouped Example:
builder.NorGroup(g => {
g.AndWhere(p => p.IsStudent)
.OrWhere(p => p.Grade > 90);
});
These are extension methods to directly combine expressions.
var adult = PredicateBuilder.Create<Person>(p => p.Age >= 18);
var livesInParis = PredicateBuilder.Create<Person>(p => p.City == "Paris");
var combined = adult.And(livesInParis); // returns Expression<Func<Person, bool>>
You can also start with:
PredicateBuilder.True<Person>(); // Always true
PredicateBuilder.False<Person>(); // Always false
var builder = new PredicateQueryBuilder<User>();
builder.AndWhere(u => u.IsActive)
.OrGroup(g => g.AndWhere(u => u.Role == "Admin")
.AndWhere(u => u.LastLogin.WithinDuration(TimeSpan.FromDays(30))))
.XorWhereNot(u => u.Email.Contains("temp"));
var predicate = builder.Build();
var users = dbContext.Users.Where(predicate.Compile()).ToList();
- Always use
Build()
to get the finalExpression<Func<T, bool>>
. - Use
Compile()
if you want to run it on in-memory collections. - For EF or LINQ-to-SQL, use the raw expression directly.