SHARE
TWEET

Untitled

a guest Aug 20th, 2019 71 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using EfCoreOverview_Demo.Entities;
  2. using System;
  3. using System.Linq;
  4. using System.Linq.Expressions;
  5.  
  6. namespace EfCoreOverview_Demo
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             var context = new TelerikAcademyContext();
  13.             var minSalaryGroups = context.Employees
  14.                 .GroupBy(e => e.DepartmentId, (key, group) => new
  15.                 {
  16.                     DepartmentId = key,
  17.                     MinSalary = group.Min(e => e.Salary)
  18.                 })
  19.                 .ToList();
  20.  
  21.             var predicate = minSalaryGroups.Aggregate(
  22.                 ToExpression((Employees x) => false),
  23.                 (expr, next) => expr.Or(e => e.DepartmentId == next.DepartmentId &&
  24.                                              e.Salary == next.MinSalary)
  25.             );
  26.  
  27.             var minSalaryEmployees = context.Employees
  28.                 .Where(predicate)
  29.                 .Select(e => new
  30.                 {
  31.                     e.FirstName,
  32.                     e.LastName,
  33.                     e.Salary,
  34.                 })
  35.                 .ToList();
  36.  
  37.         }
  38.  
  39.         public static Expression<Func<T, R>> ToExpression<T, R>(Expression<Func<T, R>> e) => e;
  40.     }
  41.  
  42.     public static class ExpressionExtensions
  43.     {
  44.         public static Expression<Func<T, bool>> Or<T>(
  45.             this Expression<Func<T, bool>> left,
  46.             Expression<Func<T, bool>> right)
  47.                 => Expression.Lambda<Func<T, bool>>(
  48.                        Expression.OrElse(
  49.                            left.Body,
  50.                            Expression.Invoke(right,left.Parameters.Cast<Expression>())),
  51.                        left.Parameters);
  52.  
  53.     }
  54. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top