🔍 Advanced LINQ = Complex Data
Simple LINQ isn’t always enough. Advanced LINQ patterns handle complex data transformations.
📝 Advanced LINQ Patterns
// Dynamic Query public IQueryableApplyFilters (IQueryable query, Dictionary filters) { foreach (var filter in filters) { var property = typeof(T).GetProperty(filter.Key); if (property != null) { query = query.Where(x => property.GetValue(x).Equals(filter.Value)); } } return query; } // Expression Tree public static Expression > BuildPredicate ( string propertyName, object value) { var parameter = Expression.Parameter(typeof(T)); var property = Expression.Property(parameter, propertyName); var constant = Expression.Constant(value); var equal = Expression.Equal(property, constant); return Expression.Lambda >(equal, parameter); } // Self-Join for Hierarchy var hierarchy = employees .Join(employees, e => e.ManagerId, m => m.Id, (e, m) => new { Employee = e.Name, Manager = m.Name, Level = 1 }); // Cross Join (Cartesian Product) var combinations = from p in products from c in colors select new { Product = p.Name, Color = c }; // Custom Aggregation var stats = data .GroupBy(x => x.Category) .Select(g => new { Category = g.Key, Count = g.Count(), Sum = g.Sum(x => x.Value), Avg = g.Average(x => x.Value), Median = g .OrderBy(x => x.Value) .Skip(g.Count() / 2) .FirstOrDefault()?.Value });
🎯 Performance Optimization
// Compile Queries private static readonly Func> GetUserById = EF.CompileAsyncQuery((MyContext ctx, int id) => ctx.Users.FirstOrDefault(u => u.Id == id)); // Batch Operations var batches = data .Select((item, index) => new { item, index }) .GroupBy(x => x.index / 100) .Select(g => g.Select(x => x.item)); // Parallel LINQ var results = data .AsParallel() .WithDegreeOfParallelism(Environment.ProcessorCount) .Where(x => IsValid(x)) .Select(x => ProcessItem(x)) .ToList(); // Caching Results private static readonly ConcurrentDictionary _cache = new(); public T GetOrAdd (string key, Func factory) { return (T)_cache.GetOrAdd(key, _ => factory()); } // Efficient Updates var itemsToUpdate = data .Where(x => x.IsActive) .Select(x => new { x.Id, UpdatedValue = x.Value * 1.1 }) .ToList();
💡 Advanced LINQ Tips
- Use compiled queries for EF Core
- Implement expression trees for dynamic queries
- Use parallel LINQ for CPU-bound operations
- Cache frequently used queries
- Use batch operations for large datasets
Advanced LINQ patterns unlock the full power of data querying. They make complex transformations elegant and efficient.
