Path: redb/redb.Examples/Examples/E190_SumAsyncFiltered.cs
Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb
Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E190_SumAsyncFiltered.cs
----
using System.Diagnostics;
using redb.Core;
using redb.Examples.Models;
using redb.Examples.Output;
namespace redb.Examples.Examples;
///
/// SumAsync with Where filter applied before aggregation.
/// Filter employees by department, then calculate total salary.
/// Tests Pro filter handling in Aggregation.
///
[ExampleMeta("E190", "SumAsync - With Filter", "Analytics",
ExampleTier.Free, 190, "Sum", "Where", "Filter", "Aggregation", RelatedApis = ["IRedbQueryable.SumAsync", "IRedbQueryable.Where"])]
public class E190_SumAsyncFiltered : ExampleBase
{
public override async Task RunAsync(IRedbService redb)
{
var sw = Stopwatch.StartNew();
// Uncomment to see generated SQL:
//var sql = await redb.Query()
// .Where(x => x.Department == "Engineering")
// .ToSqlStringAsync();
//Console.WriteLine(sql);
// Sum salaries only for Engineering department
var engineeringSalary = await redb.Query()
.Where(x => x.Department == "Engineering")
.SumAsync(x => x.Salary);
// Compare with total (no filter)
var totalSalary = await redb.Query()
.SumAsync(x => x.Salary);
// Filter and sum on nested classes: home city one level deep, floor two levels deep
var berlinFloors = await redb.Query()
.Where(x => x.HomeAddress!.City == "Berlin")
.SumAsync(x => x.HomeAddress!.Building!.Floor);
sw.Stop();
return Ok("E190", "SumAsync - With Filter", ExampleTier.Free, sw.ElapsedMilliseconds, 1,
[$"Engineering SUM: {engineeringSalary:N0}", $"Total SUM: {totalSalary:N0}", $"Ratio: {(totalSalary > 0 ? engineeringSalary / totalSalary * 100 : 0):F1}%",
$"Berlin SUM(HomeAddress.Building.Floor): {berlinFloors:N0}"]);
}
}