1+ using Hogwards . Models ;
2+ using System . Linq . Dynamic . Core ;
3+ using System . Linq . Expressions ;
4+ using Microsoft . EntityFrameworkCore ;
5+
6+ var studentData = new StudentData ( ) ;
7+ var students = studentData . GetStudents ( ) ;
8+
9+ //House.Name != null && House.Name == "RavenClaw"
10+ Console . WriteLine ( "----Where condition on property under a sub object----" ) ;
11+ Console . WriteLine ( "----House.Name == RavenClaw----" ) ;
12+ Console . WriteLine ( "----Not null check using np() function----" ) ;
13+
14+ var studentByHouseResult = students
15+ . Where ( "np(House.Name) == \" Ravenclaw\" " )
16+ . ToList ( ) ;
17+
18+ foreach ( var student in studentByHouseResult )
19+ {
20+ Console . WriteLine ( "{0}\t \t {1}\t {2}" , student . Name , student . House ? . Name , student . Age ) ;
21+ }
22+
23+
24+
25+ //Dynamically creating lambda expressions
26+ Console . WriteLine ( "\n ----Dynamic Lambda----" ) ;
27+ Console . WriteLine ( "----Students older than 14----" ) ;
28+
29+ Expression < Func < Student , bool > > itExpression = DynamicExpressionParser
30+ . ParseLambda < Student , bool > ( new ParsingConfig ( ) , true , "House.Name == @0" , "Hufflepuff" ) ;
31+
32+ Expression < Func < Student , bool > > ageExpression = DynamicExpressionParser
33+ . ParseLambda < Student , bool > ( new ParsingConfig ( ) , true , "Age >= @0" , 14 ) ;
34+
35+ var conditionCheck = "age" ;
36+ var lambdaResult = students
37+ . Where ( "@0(it)" , conditionCheck == "house" ? itExpression : ageExpression )
38+ . ToList ( ) ;
39+
40+ foreach ( var student in lambdaResult )
41+ {
42+ Console . WriteLine ( "{0}\t \t {1}\t {2}" , student . Name , student . House ? . Name , student . Age ) ;
43+ }
44+
45+
46+
47+ //Group sort
48+ Console . WriteLine ( "\n ----Group Sort----" ) ;
49+ Console . WriteLine ( "----Sort by house by descending order, then sort the students starting from elder to younger under each house----" ) ;
50+
51+ var groupSortResult = students
52+ . OrderBy ( "np(House.Name, \" \" ) asc, age desc" )
53+ . ToList ( ) ;
54+
55+ foreach ( var student in groupSortResult )
56+ {
57+ Console . WriteLine ( "{0}\t \t {1}\t {2}" , student . Name , student . House ? . Name , student . Age ) ;
58+ }
59+
60+
61+
62+ //Selecting Data Using Dynamic LINQ
63+ //public List<Student> GetStudents() =>
64+ // students
65+ // .Select(s => new Student
66+ // {
67+ // Name = s.Name,
68+ // age = s.Age,
69+ // House = s.House.House,
70+ // })
71+ // .ToList();
72+
73+ Console . WriteLine ( "\n ----Selecting Data Using Dynamic LINQ----" ) ;
74+
75+ var selectStudents = students
76+ . Select ( "new {Name, Gender, np(House.Name, \" \" ) as House}" )
77+ . ToDynamicList ( ) ;
78+
79+ foreach ( var student in selectStudents )
80+ {
81+ Console . WriteLine ( "{0}\t \t {1}\t {2}" , student . Name , student . Gender , student . House ) ;
82+ }
83+
84+ Console . WriteLine ( "\n " ) ;
0 commit comments