Expression - lucyberryhub/WPF.Tutorial GitHub Wiki

Tutorial: How Expression Helps Reduce Code Duplication in C#

πŸ“Œ What is an Expression in C#?

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.


πŸ”Ή Why Use Expression?

βœ… Avoids Code Duplication

By using Expression<Func<T, bool>>, you can pass a filtering condition dynamically instead of writing separate methods for different conditions.

βœ… Improves Maintainability

Instead of hardcoding queries in multiple places, you define one generic method that accepts different filtering conditions.


πŸ›  Example 1: Without Expression (Code Duplication)

❌ 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!


πŸ›  Example 2: With Expression (Code Simplified)

βœ… 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! πŸš€


πŸ›  Example 3: Using Expression in JSON Data Loading (Real Use Case)

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!


🎯 Key Takeaways

βœ” 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

⚠️ **GitHub.com Fallback** ⚠️