dotnet --version
Write complex LINQ queries: grouping, joins, aggregate functions, and expression tree techniques.
1 using System.Linq.Expressions; 2 3 public record Order(int Id, string CustomerId, decimal Total, DateTime Date); 4 public record Customer(string Id, string Name, string Region); 5 6 public static class LinqPatterns 7 { 8 // Pattern 1: Group + Aggregate 9 public static IEnumerable<(string CustomerId, decimal TotalRevenue, int OrderCount)> 10 GetCustomerSummary(IEnumerable<Order> orders) 11 { 12 return orders 13 .GroupBy(o => o.CustomerId) 14 .Select(g => (g.Key, g.Sum(o => o.Total), g.Count())) 15 .OrderByDescending(x => x.Item2); 16 } 17 18 // Pattern 2: Left outer join 19 public static IEnumerable<(Customer Customer, Order? LatestOrder)> 20 GetCustomersWithLatestOrder(IEnumerable<Customer> customers, IEnumerable<Order> orders) 21 { 22 return customers 23 .GroupJoin( 24 orders, 25 c => c.Id, 26 o => o.CustomerId, 27 (customer, customerOrders) => ( 28 Customer: customer, 29 LatestOrder: customerOrders.OrderByDescending(o => o.Date).FirstOrDefault() 30 ) 31 ); 32 } 33 34 // Pattern 3: Batch processing with Chunk 35 public static async Task ProcessInBatchesAsync(IEnumerable<Order> orders, int batchSize = 100) 36 { 37 foreach (var batch in orders.Chunk(batchSize)) 38 { 39 await ProcessBatchAsync(batch); 40 } 41 } 42 43 private static Task ProcessBatchAsync(Order[] batch) => Task.CompletedTask; 44 45 // Pattern 4: Custom extension method 46 public static IEnumerable<T> TopN<T>(this IEnumerable<T> source, int n, Func<T, IComparable> selector) 47 => source.OrderByDescending(selector).Take(n); 48 } 49 50 // Pattern 5: Dynamic Where with Expression Trees 51 public static class DynamicFilter 52 { 53 public static Func<T, bool> BuildFilter<T>(string propertyName, object value) 54 { 55 var param = Expression.Parameter(typeof(T), "x"); 56 var prop = Expression.Property(param, propertyName); 57 var constant = Expression.Constant(Convert.ChangeType(value, prop.Type)); 58 var equals = Expression.Equal(prop, constant); 59 return Expression.Lambda<Func<T, bool>>(equals, param).Compile(); 60 } 61 } 62
Sign in to share your feedback and join the discussion.