Expression - lucyberryhub/WPF.Tutorial GitHub Wiki
An Expression<T>
in C# represents a piece of code (usually a lambda function) that can be passed around, compiled, and executed later. Itβs commonly used in LINQ queries and Entity Framework to filter data dynamically.
By using Expression<Func<T, bool>>
, you can pass a filtering condition dynamically instead of writing separate methods for different conditions.
Instead of hardcoding queries in multiple places, you define one generic method that accepts different filtering conditions.
β Before using Expression
, you may have multiple similar methods:
public async Task<List<User>> GetActiveUsers()
{
using var dbContext = new AppDbContext();
return await dbContext.Users.Where(u => u.IsActive).ToListAsync();
}
public async Task<List<User>> GetUsersByRole(string role)
{
using var dbContext = new AppDbContext();
return await dbContext.Users.Where(u => u.Role == role).ToListAsync();
}
π΄ The problem? Both methods do nearly the same thing but with different filters!
β
Using Expression<Func<T, bool>>
, we can combine these methods into one generic method:
public async Task<List<T>> GetEntities<T>(Expression<Func<T, bool>> filter = null) where T : class
{
using var dbContext = new AppDbContext();
var query = dbContext.Set<T>();
if (filter != null)
{
query = query.Where(filter);
}
return await query.ToListAsync();
}
Now, you can use this single method to query any data with different conditions!
var activeUsers = await GetEntities<User>(u => u.IsActive);
var admins = await GetEntities<User>(u => u.Role == "Admin");
β One method instead of multiple duplicates! π
In our improved LoadDataFromDatabaseToJson
method, we applied this principle:
public async Task LoadDataFromDatabaseToJson<T>(Expression<Func<T, bool>> whereCondition = null) where T : class, new()
{
using var dbContext = new AppDbContext();
var dbSet = dbContext.GetDbSet<T>();
// Apply filter dynamically
var query = whereCondition != null ? dbSet.Where(whereCondition) : dbSet;
var data = await query.ToListAsync();
await JsonHelper.WriteToJsonFileAsync(tempJsonFile, data);
}
// Usage:
await LoadDataFromDatabaseToJson<User>(u => u.IsActive);
await LoadDataFromDatabaseToJson<Product>(p => p.Price > 100);
πΉ Instead of writing different methods for each case, we now pass the filter dynamically as a parameter!
β Expression<Func<T, bool>>
helps us write reusable and flexible methods
β It eliminates code duplication and makes code more maintainable
β It is commonly used in LINQ and Entity Framework for querying data dynamically