C# 3.0 Language Innovations
                                                    Query
                 var CommonWords =                  expressions
                   from w in wordOccurances
                   where w.Count > 2
Local variable     select new { f.Name, w.Word, W.Count };
type inference

                                 Lambda
                                 expressions
                 var CommonWords =
                   wordOccurances
                   .Where(w => w.Count > 2)
                   .Select(w => new {f.Name, w.Word, W.Count });
Extension
methods            Anonymous                    Object
                   types                        initializers
                                                                  1
Lambda Expressions
 public delegate bool Predicate<T>(T obj);

 public class List<T>
 {                                                 Statement
    public List<T> FindAll(Predicate<T> test) { … } context
   Explicitly
    … typed
 }                                                          Implicitly
       List<Customer> customers =                            typed
       GetCustomerList();
   List<Customer> x = customers.FindAll(                        Expression
       delegate(Customer c) { return c.State == "WA"; }           context
   );


  List<Customer> x = customers.FindAll(c => c.State == "WA");




                                                                             2
Lambda Expressions
 public delegate T Func<T>();
 public delegate T Func<A0, T>(A0 arg0);
 public delegate T Func<A0, A1, T>(A0 arg0, A1
 arg1);
 …
 Func<Customer, bool> test = c => c.State == "WA";

 double factor = 2.0;
 Func<double, double> f = x => x * factor;

 Func<int, int, int> f = (x, y) => x * y;

 Func<int, int, int> comparer =
   (int x, int y) => {
      if (x > y) return 1;
      if (x < y) return -1;
      return 0;
   };
                                                     3
Queries Through APIs
                                       Query operators
                                       are just methods
 public class List<T>
 {
   public List<T> Where(Func<T, bool> predicate) { … }
   public List<S> Select<S>(Func<T, S> selector) { … }
   …
 }                                                        Methods compose
                                                           to form queries
       List<Customer> customers = GetCustomerList();

   List<string> contacts =
      customers.Where(c => c.State == "WA").Select(c =>
   c.Name);
 But what about
  other types?     Declare operators
                    in all collections?               Type inference
                                                      figures out <S>
             What about
               arrays?

                                                                             4
Queries Through APIs
                                            Query operators
                                           are static methods
 public static class Sequence
 {
   public static IEnumerable<T> Where<T>(IEnumerable<T> source,
      Func<T, bool> predicate) { … }

   public static IEnumerable<S> Select<T, S>(IEnumerable<T> source,
     Func<T, S> selector) { … }
   …
 }                                                            Huh?
          Customer[] customers = GetCustomerArray();

      IEnumerable<string> contacts = Sequence.Select(
          Sequence.Where(customers, c => c.State == "WA"),
          c => c.Name);


                                   Want methods on
                                   IEnumerable<T>

                                                                      5
Extension Methods
class Customer { public string Name; }

Customer[ ] c = new Customer[1];

c._


              Huh ?!!?!




                                         6
Extension Methods
                                                    Extension
 namespace System.Query                             methods
 {
   public static class Sequence
   {
     public static IEnumerable<T> Where<T>(this IEnumerable<T> source,
        Func<T, bool> predicate) { … }

      public static IEnumerable<S> Select<T, S>(this IEnumerable<T>
 source,                                                  obj.Foo(x, y)
         Func<T, S> selector) { … }     Brings                 
      …                             extensions into     XXX.Foo(obj, x, y)
   }                                    scope
 }     using System.Query;

  IEnumerable<string> contacts =
    customers.Where(c => c.State == "WA").Select(c =>
  c.Name);

                  IntelliSense!

                                                                             7
Extension Methods


public static class MyExtensions
{
   public static IEnumerable<T> Where<T>(
                this IEnumerable<T> source,
                Func<T, bool> predicate)
   {
      foreach (T item in source)
        if (predicate(item))
          yield return item;
    }
  }


                                              8
Extension Methods
                                  Method is named
                                      ‘Where’


public static class MyExtensions
{
   public static IEnumerable<T> Where<T>(
                this IEnumerable<T> source,
                Func<T, bool> predicate)
   {
      foreach (T item in source)
        if (predicate(item))
          yield return item;
    }
  }


                                                    9
Extension Methods
                                  Method is named
                                      ‘Where’


public static class MyExtensions                     Method extends
{                                                    objects of type
                                                    IEnumerable<T>
   public static IEnumerable<T> Where<T>(
                this IEnumerable<T> source,
                Func<T, bool> predicate)
   {
      foreach (T item in source)
        if (predicate(item))
          yield return item;
    }
  }


                                                                   10
Extension Methods
                                       Method is named
                                           ‘Where’


public static class MyExtensions                           Method extends
{                                                          objects of type
                                                          IEnumerable<T>
   public static IEnumerable<T> Where<T>(
                this IEnumerable<T> source,
                Func<T, bool> predicate)
   {
      foreach (T item in source)
        if (predicate(item))
          yield return item;             Implementation
    }
  }


                                                                         11
Extension Methods
                                        Method is named
                                            ‘Where’


public static class MyExtensions                           Method extends
{                                                          objects of type
                                                          IEnumerable<T>
   public static IEnumerable<T> Where<T>(
                this IEnumerable<T> source,
                Func<T, bool> predicate)
                                                          Signature of the
   {                                                    predicate parameter
      foreach (T item in source)
        if (predicate(item))
          yield return item;             Implementation
    }
  }


                                                                         12
Extension Methods
                                        Method is named
                                            ‘Where’


public static class MyExtensions                           Method extends
{                                                          objects of type
                                                          IEnumerable<T>
   public static IEnumerable<T> Where<T>(
                this IEnumerable<T> source,
                Func<T, bool> predicate)
                                                          Signature of the
   {                                                    predicate parameter
      foreach (T item in source)
        if (predicate(item))
          yield return item;             Implementation
    }
  } string[] names = { "Burke", "Connor", "Frank“ };
   IEnumerable<string> expr = MyExtensions.Where(names,
                            s => s.Length < 6);
                                                                         13
Extension Methods
                                        Method is named
                                            ‘Where’
[System.Runtime.CompilerServices.Extension]
public static class MyExtensions                           Method extends
{                                                          objects of type
                                                          IEnumerable<T>
   public static IEnumerable<T> Where<T>(
                this IEnumerable<T> source,
                Func<T, bool> predicate)
                                                          Signature of the
   {                                                    predicate parameter
      foreach (T item in source)
        if (predicate(item))
          yield return item;             Implementation
    }
  } string[] names = { "Burke", "Connor", "Frank“ };
   IEnumerable<string> expr = names.Where(names,
                            s => s.Length < 6);
                                                                         14
Anonymous Types
 public class Customer
 {
   public string Name;
   public Address Address;         public class Contact
   public string Phone;            {        class ???
   public List<Order> Orders;        public{string Name;
   …                                 public string Phone; Name;
                                               public string
 }                                 }           public string Phone;
Customer c = GetCustomer(…);                }
Contact x = new Contact { Name = c.Name, Phone = c.Phone };

Customer c = GetCustomer(…);
var x = new { Name = c.Name, Phone = c.Phone };

                                              Projection style
Customer c = GetCustomer(…);                     initializer
var x = new { c.Name, c.Phone };


                                                                      15
Anonymous Types
       var contacts =
         from c in customers
         where c.State == "WA"
         select new { c.Name, c.Phone };    class ???
                                            {
        IEnumerable<???>                       public string Name;
                                               public string Phone;
                                            }
       var contacts =
         customers.
         .Where(c => c.State == "WA“)
         .Select(c => new { c.Name, c.Phone });
 ???

       foreach (var c in contacts) {
          Console.WriteLine(c.Name);
          Console.WriteLine(c.Phone);
       }

                                                                      16
Object Initializers
 public class Point
 {
   private int x, y;

     public int X { get { return x; } set { x = value; } }   Field or property
     public int Y { get { return y; } set { y = value; } }     assignments
 }


               Point a = new Point { X = 0, Y = 1 };




               Point a = new Point();
               a.X = 0;
               a.Y = 1;



                                                                                 17
Object Initializers
                                              Embedded
 public class Rectangle                        objects
 {
   private Point p1 = new Point();
   private Point p2 = new Point();                Read-only
                                                  properties
     public Point P1 { get { return p1; } }
     public Point P2 { get { return p2; } }
 }
            Rectangle r = new Rectangle {
               P1 = { X = 0, Y = 1 },
               P2 = { X = 2, Y = 3 }          No “new Point”
            };


            Rectangle r = new Rectangle();
            r.P1.X = 0;
            r.P1.Y = 1;
            r.P2.X = 2;
            r.P2.Y = 3;

                                                               18
Collection Initializers
                                     Must implement
                                     ICollection<T>


 List<int> powers = new List<int> { 1, 10, 100, 1000,
 10000 };
                      List<int> powers = new List<int>();
                      powers.Add(1);
                      powers.Add(10);
                      powers.Add(100);
                      powers.Add(1000);
                      powers.Add(10000);




                                                            19
Collection Initializers
 public class Contact
 {
   private string name;
   private List<string> phoneNumbers = new List<string>();

     public string Name { get { return name; } set { name = value; } }
     public List<string> PhoneNumbers { get { return phoneNumbers; } }
 }
         List<Contact> contacts = new List<Contact> {
            new Contact {
               Name = "Chris Smith",
               PhoneNumbers = { "206-555-0101", "425-882-8080" }
            },
            new Contact {
               Name = "Bob Harris",
               PhoneNumbers = { "650-555-0199" }
            }
         };

                                                                         20
Local Variable Type Inference
   int i = 5;
   string s = "Hello";
   double d = 1.0;
   int[] numbers = new int[] {1, 2, 3};
   Dictionary<int,Order> orders = new Dictionary<int,Order>();


   var i = 5;
   var s = "Hello";
   var d = 1.0;
   var numbers = new int[] {1, 2, 3};
   var orders = new Dictionary<int,Order>();


      “var” means same
       type as initializer


                                                                 21
Expression Trees
 public class Northwind: DataContext
 {
   public Table<Customer> Customers;
   public Table<Order> Orders;                        How does this
   …                                                  get remoted?
 }
    Northwind db = new Northwind(…);
    var query = from c in db.Customers where c.State == "WA" select c;

   Northwind db = new Northwind(…);                      Method asks for
   var query = db.Customers.Where(c => c.State ==        expression tree
   "WA");
 public class Table<T>: IEnumerable<T>
 {
   public Table<T> Where(Expression<Func<T, bool>> predicate);
   …
 }
                                     System.Expressions.
                                       Expression<T>
                                                                           22
Expression Trees
 Code as Data
              Func<Customer, bool> test = c => c.State == "WA";


  Expression<Func<Customer, bool>> test = c => c.State == "WA";


  ParameterExpression c =
     Expression.Parameter(typeof(Customer), "c");
  Expression expr =
     Expression.EQ(
        Expression.Property(c,
  typeof(Customer).GetProperty("State")),
        Expression.Constant("WA")
     );
  Expression<Func<Customer, bool>> test =
     Expression.Lambda<Func<Customer, bool>>(expr, c);

                                                                  23
Query Expressions
  Language integrated query syntax

                            Starts with
                              from          Zero or more
                                           from or where
from id in source
{ from id in source | where condition }         Optional
[ orderby ordering, ordering, … ]               orderby
select expr | group expr by key
[ into id query ]                         Ends with select
                         Optional into      or group by
                         continuation


                                                             24
Query Expressions
 Queries translate to method invocations
   Where, Select, SelectMany, OrderBy, GroupBy

    from c in customers
    where c.State == "WA"
    select new { c.Name, c.Phone };


    customers
    .Where(c => c.State == "WA")
    .Select(c => new { c.Name, c.Phone });

                                             25
C# 3.0 Language Innovations
 Lambda expressions            c => c.Name


 Extension methods          static void Dump(this object o);


 Local variable type inference               var x = 5;

 Object initializers     new Point { x = 1, y = 2 }

 Anonymous types                 new { c.Name,
                                 c.Phone }
 Query expressions
                          from … where …
 Expression trees         select

                       Expression<T>
                                                               26

More Related Content

PPTX
Generics in .NET, C++ and Java
PPTX
Lecture 7 arrays
PPT
Generics
PPTX
C# Generics
PDF
The Ring programming language version 1.4 book - Part 9 of 30
PPTX
Linq Sanjay Vyas
PDF
Pragmatic functional refactoring with java 8 (1)
PDF
The Ring programming language version 1.8 book - Part 38 of 202
Generics in .NET, C++ and Java
Lecture 7 arrays
Generics
C# Generics
The Ring programming language version 1.4 book - Part 9 of 30
Linq Sanjay Vyas
Pragmatic functional refactoring with java 8 (1)
The Ring programming language version 1.8 book - Part 38 of 202

What's hot (20)

PPT
Oop objects_classes
PDF
The Ring programming language version 1.5.2 book - Part 32 of 181
PDF
Modul Praktek Java OOP
PDF
The Ring programming language version 1.5 book - Part 6 of 31
PDF
The Ring programming language version 1.5.4 book - Part 33 of 185
PDF
Pragmatic functional refactoring with java 8
PPTX
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
PDF
The Ring programming language version 1.4.1 book - Part 9 of 31
PDF
The Ring programming language version 1.3 book - Part 24 of 88
PPTX
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
PPTX
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
PDF
Object Oriented Solved Practice Programs C++ Exams
PDF
The Ring programming language version 1.5.1 book - Part 31 of 180
PPTX
Introduction to Client-Side Javascript
PPTX
Java generics
PDF
The Ring programming language version 1.5.3 book - Part 31 of 184
PDF
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
PDF
C# Summer course - Lecture 3
PDF
The Ring programming language version 1.7 book - Part 36 of 196
PDF
3. Объекты, классы и пакеты в Java
Oop objects_classes
The Ring programming language version 1.5.2 book - Part 32 of 181
Modul Praktek Java OOP
The Ring programming language version 1.5 book - Part 6 of 31
The Ring programming language version 1.5.4 book - Part 33 of 185
Pragmatic functional refactoring with java 8
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
The Ring programming language version 1.4.1 book - Part 9 of 31
The Ring programming language version 1.3 book - Part 24 of 88
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
Object Oriented Solved Practice Programs C++ Exams
The Ring programming language version 1.5.1 book - Part 31 of 180
Introduction to Client-Side Javascript
Java generics
The Ring programming language version 1.5.3 book - Part 31 of 184
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
C# Summer course - Lecture 3
The Ring programming language version 1.7 book - Part 36 of 196
3. Объекты, классы и пакеты в Java
Ad

Viewers also liked (20)

PDF
Quy trinh sx mu cua cty cao su dong phu binh phuoc
PPT
Banking K42 2005
PDF
Donald j trump_trump_the_art_of_the_deal.thegioiebook.com
PDF
San sustainable agriculture standard april 2009
PDF
Vt utz coc_coffee_v2009
PDF
Ung dung excel trong kinh te
PPT
Genetic modified-crops-1228274479307533-9
PDF
PHÁO ĐẦU (CHINA CHESS)
PPT
Technology In The Classroom
PPS
Banngheo 100329013057-phpapp01
PDF
Dan brown angelsanddemons
PPTX
Info Session (F08)
PDF
Binh phong ma co dien toan tap 2 (china chess)
PDF
Vegetables. growing asparagus in the home garden
PDF
quất trung bì tập 2 (china chess)
PPT
Mr. Thong Presentation Vn 2009
PPTX
Today Is Tuesday
PDF
ông già và biển cả
PDF
Tcvn 3769 2004
PPT
Sars update march 2004 vietnamese1ud
Quy trinh sx mu cua cty cao su dong phu binh phuoc
Banking K42 2005
Donald j trump_trump_the_art_of_the_deal.thegioiebook.com
San sustainable agriculture standard april 2009
Vt utz coc_coffee_v2009
Ung dung excel trong kinh te
Genetic modified-crops-1228274479307533-9
PHÁO ĐẦU (CHINA CHESS)
Technology In The Classroom
Banngheo 100329013057-phpapp01
Dan brown angelsanddemons
Info Session (F08)
Binh phong ma co dien toan tap 2 (china chess)
Vegetables. growing asparagus in the home garden
quất trung bì tập 2 (china chess)
Mr. Thong Presentation Vn 2009
Today Is Tuesday
ông già và biển cả
Tcvn 3769 2004
Sars update march 2004 vietnamese1ud
Ad

Similar to C# 3.0 Language Innovations (20)

PPTX
Mixing functional programming approaches in an object oriented language
PPTX
Lesson11
PPT
Understanding linq
PPT
Generic Types in Java (for ArtClub @ArtBrains Software)
PPTX
Linq Introduction
PPT
Lo Mejor Del Pdc2008 El Futrode C#
PPTX
Whats New In C# 4 0 - NetPonto
PPT
Generics_RIO.ppt
PPTX
Introducción a LINQ
PPTX
Linq and lambda
PPT
devLink - What's New in C# 4?
PDF
Ds lab handouts
PPT
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
PPT
Introduction to Linq
PDF
Java8: Language Enhancements
PDF
Java 8 Workshop
PDF
JAVA PROGRAMMING - The Collections Framework
PDF
Get Functional on the CLR: Intro to Functional Programming with F#
PPTX
Lambda expressions
PPTX
Monadic Comprehensions and Functional Composition with Query Expressions
Mixing functional programming approaches in an object oriented language
Lesson11
Understanding linq
Generic Types in Java (for ArtClub @ArtBrains Software)
Linq Introduction
Lo Mejor Del Pdc2008 El Futrode C#
Whats New In C# 4 0 - NetPonto
Generics_RIO.ppt
Introducción a LINQ
Linq and lambda
devLink - What's New in C# 4?
Ds lab handouts
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Introduction to Linq
Java8: Language Enhancements
Java 8 Workshop
JAVA PROGRAMMING - The Collections Framework
Get Functional on the CLR: Intro to Functional Programming with F#
Lambda expressions
Monadic Comprehensions and Functional Composition with Query Expressions

More from Shahriar Hyder (8)

PPTX
Effective Communication Skills for Software Engineers
DOCX
A JavaScript Master Class - From the Wows to the WTFs
PPTX
Dependency Inversion Principle
PPTX
Bridge Design Pattern
PPT
Command Design Pattern
PPTX
Taking a Quantum Leap with Html 5 WebSocket
PPTX
Functional Programming Fundamentals
PPT
Object Relational Mapping with LINQ To SQL
Effective Communication Skills for Software Engineers
A JavaScript Master Class - From the Wows to the WTFs
Dependency Inversion Principle
Bridge Design Pattern
Command Design Pattern
Taking a Quantum Leap with Html 5 WebSocket
Functional Programming Fundamentals
Object Relational Mapping with LINQ To SQL

Recently uploaded (20)

PDF
A review of recent deep learning applications in wood surface defect identifi...
DOCX
search engine optimization ppt fir known well about this
PDF
NewMind AI Weekly Chronicles – August ’25 Week III
PPTX
Final SEM Unit 1 for mit wpu at pune .pptx
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PDF
Taming the Chaos: How to Turn Unstructured Data into Decisions
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
PPTX
Modernising the Digital Integration Hub
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
PPTX
The various Industrial Revolutions .pptx
PDF
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PDF
DP Operators-handbook-extract for the Mautical Institute
PDF
1 - Historical Antecedents, Social Consideration.pdf
PDF
A novel scalable deep ensemble learning framework for big data classification...
PDF
A Late Bloomer's Guide to GenAI: Ethics, Bias, and Effective Prompting - Boha...
PDF
August Patch Tuesday
PPTX
observCloud-Native Containerability and monitoring.pptx
A review of recent deep learning applications in wood surface defect identifi...
search engine optimization ppt fir known well about this
NewMind AI Weekly Chronicles – August ’25 Week III
Final SEM Unit 1 for mit wpu at pune .pptx
Univ-Connecticut-ChatGPT-Presentaion.pdf
Taming the Chaos: How to Turn Unstructured Data into Decisions
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
Modernising the Digital Integration Hub
Group 1 Presentation -Planning and Decision Making .pptx
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
The various Industrial Revolutions .pptx
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
DP Operators-handbook-extract for the Mautical Institute
1 - Historical Antecedents, Social Consideration.pdf
A novel scalable deep ensemble learning framework for big data classification...
A Late Bloomer's Guide to GenAI: Ethics, Bias, and Effective Prompting - Boha...
August Patch Tuesday
observCloud-Native Containerability and monitoring.pptx

C# 3.0 Language Innovations

  • 1. C# 3.0 Language Innovations Query var CommonWords = expressions from w in wordOccurances where w.Count > 2 Local variable select new { f.Name, w.Word, W.Count }; type inference Lambda expressions var CommonWords = wordOccurances .Where(w => w.Count > 2) .Select(w => new {f.Name, w.Word, W.Count }); Extension methods Anonymous Object types initializers 1
  • 2. Lambda Expressions public delegate bool Predicate<T>(T obj); public class List<T> { Statement public List<T> FindAll(Predicate<T> test) { … } context Explicitly … typed } Implicitly List<Customer> customers = typed GetCustomerList(); List<Customer> x = customers.FindAll( Expression delegate(Customer c) { return c.State == "WA"; } context ); List<Customer> x = customers.FindAll(c => c.State == "WA"); 2
  • 3. Lambda Expressions public delegate T Func<T>(); public delegate T Func<A0, T>(A0 arg0); public delegate T Func<A0, A1, T>(A0 arg0, A1 arg1); … Func<Customer, bool> test = c => c.State == "WA"; double factor = 2.0; Func<double, double> f = x => x * factor; Func<int, int, int> f = (x, y) => x * y; Func<int, int, int> comparer = (int x, int y) => { if (x > y) return 1; if (x < y) return -1; return 0; }; 3
  • 4. Queries Through APIs Query operators are just methods public class List<T> { public List<T> Where(Func<T, bool> predicate) { … } public List<S> Select<S>(Func<T, S> selector) { … } … } Methods compose to form queries List<Customer> customers = GetCustomerList(); List<string> contacts = customers.Where(c => c.State == "WA").Select(c => c.Name); But what about other types? Declare operators in all collections? Type inference figures out <S> What about arrays? 4
  • 5. Queries Through APIs Query operators are static methods public static class Sequence { public static IEnumerable<T> Where<T>(IEnumerable<T> source, Func<T, bool> predicate) { … } public static IEnumerable<S> Select<T, S>(IEnumerable<T> source, Func<T, S> selector) { … } … } Huh? Customer[] customers = GetCustomerArray(); IEnumerable<string> contacts = Sequence.Select( Sequence.Where(customers, c => c.State == "WA"), c => c.Name); Want methods on IEnumerable<T> 5
  • 6. Extension Methods class Customer { public string Name; } Customer[ ] c = new Customer[1]; c._ Huh ?!!?! 6
  • 7. Extension Methods Extension namespace System.Query methods { public static class Sequence { public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> predicate) { … } public static IEnumerable<S> Select<T, S>(this IEnumerable<T> source, obj.Foo(x, y) Func<T, S> selector) { … } Brings  … extensions into XXX.Foo(obj, x, y) } scope } using System.Query; IEnumerable<string> contacts = customers.Where(c => c.State == "WA").Select(c => c.Name); IntelliSense! 7
  • 8. Extension Methods public static class MyExtensions { public static IEnumerable<T> Where<T>( this IEnumerable<T> source, Func<T, bool> predicate) { foreach (T item in source) if (predicate(item)) yield return item; } } 8
  • 9. Extension Methods Method is named ‘Where’ public static class MyExtensions { public static IEnumerable<T> Where<T>( this IEnumerable<T> source, Func<T, bool> predicate) { foreach (T item in source) if (predicate(item)) yield return item; } } 9
  • 10. Extension Methods Method is named ‘Where’ public static class MyExtensions Method extends { objects of type IEnumerable<T> public static IEnumerable<T> Where<T>( this IEnumerable<T> source, Func<T, bool> predicate) { foreach (T item in source) if (predicate(item)) yield return item; } } 10
  • 11. Extension Methods Method is named ‘Where’ public static class MyExtensions Method extends { objects of type IEnumerable<T> public static IEnumerable<T> Where<T>( this IEnumerable<T> source, Func<T, bool> predicate) { foreach (T item in source) if (predicate(item)) yield return item; Implementation } } 11
  • 12. Extension Methods Method is named ‘Where’ public static class MyExtensions Method extends { objects of type IEnumerable<T> public static IEnumerable<T> Where<T>( this IEnumerable<T> source, Func<T, bool> predicate) Signature of the { predicate parameter foreach (T item in source) if (predicate(item)) yield return item; Implementation } } 12
  • 13. Extension Methods Method is named ‘Where’ public static class MyExtensions Method extends { objects of type IEnumerable<T> public static IEnumerable<T> Where<T>( this IEnumerable<T> source, Func<T, bool> predicate) Signature of the { predicate parameter foreach (T item in source) if (predicate(item)) yield return item; Implementation } } string[] names = { "Burke", "Connor", "Frank“ }; IEnumerable<string> expr = MyExtensions.Where(names, s => s.Length < 6); 13
  • 14. Extension Methods Method is named ‘Where’ [System.Runtime.CompilerServices.Extension] public static class MyExtensions Method extends { objects of type IEnumerable<T> public static IEnumerable<T> Where<T>( this IEnumerable<T> source, Func<T, bool> predicate) Signature of the { predicate parameter foreach (T item in source) if (predicate(item)) yield return item; Implementation } } string[] names = { "Burke", "Connor", "Frank“ }; IEnumerable<string> expr = names.Where(names, s => s.Length < 6); 14
  • 15. Anonymous Types public class Customer { public string Name; public Address Address; public class Contact public string Phone; { class ??? public List<Order> Orders; public{string Name; … public string Phone; Name; public string } } public string Phone; Customer c = GetCustomer(…); } Contact x = new Contact { Name = c.Name, Phone = c.Phone }; Customer c = GetCustomer(…); var x = new { Name = c.Name, Phone = c.Phone }; Projection style Customer c = GetCustomer(…); initializer var x = new { c.Name, c.Phone }; 15
  • 16. Anonymous Types var contacts = from c in customers where c.State == "WA" select new { c.Name, c.Phone }; class ??? { IEnumerable<???> public string Name; public string Phone; } var contacts = customers. .Where(c => c.State == "WA“) .Select(c => new { c.Name, c.Phone }); ??? foreach (var c in contacts) { Console.WriteLine(c.Name); Console.WriteLine(c.Phone); } 16
  • 17. Object Initializers public class Point { private int x, y; public int X { get { return x; } set { x = value; } } Field or property public int Y { get { return y; } set { y = value; } } assignments } Point a = new Point { X = 0, Y = 1 }; Point a = new Point(); a.X = 0; a.Y = 1; 17
  • 18. Object Initializers Embedded public class Rectangle objects { private Point p1 = new Point(); private Point p2 = new Point(); Read-only properties public Point P1 { get { return p1; } } public Point P2 { get { return p2; } } } Rectangle r = new Rectangle { P1 = { X = 0, Y = 1 }, P2 = { X = 2, Y = 3 } No “new Point” }; Rectangle r = new Rectangle(); r.P1.X = 0; r.P1.Y = 1; r.P2.X = 2; r.P2.Y = 3; 18
  • 19. Collection Initializers Must implement ICollection<T> List<int> powers = new List<int> { 1, 10, 100, 1000, 10000 }; List<int> powers = new List<int>(); powers.Add(1); powers.Add(10); powers.Add(100); powers.Add(1000); powers.Add(10000); 19
  • 20. Collection Initializers public class Contact { private string name; private List<string> phoneNumbers = new List<string>(); public string Name { get { return name; } set { name = value; } } public List<string> PhoneNumbers { get { return phoneNumbers; } } } List<Contact> contacts = new List<Contact> { new Contact { Name = "Chris Smith", PhoneNumbers = { "206-555-0101", "425-882-8080" } }, new Contact { Name = "Bob Harris", PhoneNumbers = { "650-555-0199" } } }; 20
  • 21. Local Variable Type Inference int i = 5; string s = "Hello"; double d = 1.0; int[] numbers = new int[] {1, 2, 3}; Dictionary<int,Order> orders = new Dictionary<int,Order>(); var i = 5; var s = "Hello"; var d = 1.0; var numbers = new int[] {1, 2, 3}; var orders = new Dictionary<int,Order>(); “var” means same type as initializer 21
  • 22. Expression Trees public class Northwind: DataContext { public Table<Customer> Customers; public Table<Order> Orders; How does this … get remoted? } Northwind db = new Northwind(…); var query = from c in db.Customers where c.State == "WA" select c; Northwind db = new Northwind(…); Method asks for var query = db.Customers.Where(c => c.State == expression tree "WA"); public class Table<T>: IEnumerable<T> { public Table<T> Where(Expression<Func<T, bool>> predicate); … } System.Expressions. Expression<T> 22
  • 23. Expression Trees Code as Data Func<Customer, bool> test = c => c.State == "WA"; Expression<Func<Customer, bool>> test = c => c.State == "WA"; ParameterExpression c = Expression.Parameter(typeof(Customer), "c"); Expression expr = Expression.EQ( Expression.Property(c, typeof(Customer).GetProperty("State")), Expression.Constant("WA") ); Expression<Func<Customer, bool>> test = Expression.Lambda<Func<Customer, bool>>(expr, c); 23
  • 24. Query Expressions Language integrated query syntax Starts with from Zero or more from or where from id in source { from id in source | where condition } Optional [ orderby ordering, ordering, … ] orderby select expr | group expr by key [ into id query ] Ends with select Optional into or group by continuation 24
  • 25. Query Expressions Queries translate to method invocations Where, Select, SelectMany, OrderBy, GroupBy from c in customers where c.State == "WA" select new { c.Name, c.Phone }; customers .Where(c => c.State == "WA") .Select(c => new { c.Name, c.Phone }); 25
  • 26. C# 3.0 Language Innovations Lambda expressions c => c.Name Extension methods static void Dump(this object o); Local variable type inference var x = 5; Object initializers new Point { x = 1, y = 2 } Anonymous types new { c.Name, c.Phone } Query expressions from … where … Expression trees select Expression<T> 26