100 likes | 254 Views
LINQ - 2. Ravi Kumar C++/C# Team. A LINQ Query (once again)…. Anonymous Types!. New “on the fly” class with read-only properties. var p = new { X = 0, Y = 1 }; Console.WriteLine ("(X,Y) Coords = ({0},{1})", p.X , p.Y );. Console.WriteLine ("The typename is {0}", p.GetType ().Name);.
E N D
LINQ - 2 Ravi Kumar C++/C# Team
Anonymous Types! • New “on the fly” class with read-only properties. var p = new { X = 0, Y = 1 }; Console.WriteLine("(X,Y) Coords = ({0},{1})", p.X, p.Y); Console.WriteLine("The typename is {0}",p.GetType().Name); <>f__AnonymousType1`2[System.Int32,System.Int32].
Query Expression! • Set of clauses written in a new declarative syntax (SQL like). • Starts with: From clause. • Must end with: select or group clause. • Type-checked. • More clause: where, orderby, join. (etc..) • Source of QE: IEnumerable. • Returns: IEnumerable<T>
Contextual Keywords! • New QE clauses. • E.g.: From, select, etc… • Keywords in context of QE. int from = 0; OK Var x = from c in customer Where c.Name == “ME” Select new {c.Name, c.Age}; Query Expression
QE -> Method Invocation List<int> scores = new List<int> { 77, 98, 92, 85, 80 }; IEnumerable<int> query = from score in scores where score >= 90 select score; Compiler translation List<int> scores = new List<int> { 77, 98, 92, 85, 80 }; var query = scores.Where(score => score >= 90).Select(score => score); System.Linq.Enumerablenamespace. where and select are ext methods in
Translation of QE! from score in scores where score >= 90 select score; • Source object. (scores) • where clause -> Where(…) • Parameter -> lambda exp with variable and exp in clause • scores.Where( score => score >= 90) • Enumerable.Where<int>( Func<int,bool>). • Select clause -> Select(…)
Standard Query Operators • System.Linq.Enumerable class. • Example: Where(), Select(), OrderBy(), Distinct(), Average(), Max(), Min() etc… • These Extension methods are collectively known as the Standard Query Operators. • http://msdn2.microsoft.com/en-us/vcsharp/aa336746.aspx
Expression Trees… • Data representation of the code that a C# lambda expression would execute if the expression were compiled to IL. • parsing which the compiler generates executable code. • Parsed code that has not been compiled to IL.