C# 3.0 Tom Roeder CS215 2006fa. Version 3 From PDC 2005 preview compiler available LINQ: language-integrated query High level points: adds native query.

Slides:



Advertisements
Similar presentations
Developer Knowledge Sharing Eric Sun Dec, What programming language did you learn in school and since then? Now, its time to refresh …
Advertisements

The Microsoft Technical Roadshow 2007 Language Enhancements and LINQ Daniel Moth Developer & Platform Group Microsoft Ltd
LINQ and Collections An introduction to LINQ and Collections.
ICE1341 Programming Languages Spring 2005 Lecture #13 Lecture #13 In-Young Ko iko.AT. icu.ac.kr iko.AT. icu.ac.kr Information and Communications University.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek.
Extension Methods, Anonymous Types LINQ Query Keywords, Lambda Expressions Svetlin Nakov Telerik Corporation
Copyright © 2012 Pearson Education, Inc. Chapter 9 Delegates and Events.
C# 3.0 & LINQ Raimond Brookman – IT Architect
LINQ: Language-Integrated Queries (To be included in C # 3.0) Technology developed by Anders Hejlsberg & friends at Microsoft (2005) Presented by Tal Cohen.
2.3 Cool features in C# academy.zariba.com 1. Lecture Content 1.Extension Methods 2.Anonymous Types 3.Delegates 4.Action and Func 5.Events 6.Lambda Expressions.
Delegates and Events Tom Roeder CS fa. Motivation – Function Pointers Treat functions as first-class objects eg. Scheme: (map myfunc somelist)
A tour of new features introducing LINQ. Agenda of LINQ Presentation We have features for every step of the way LINQ Fundamentals Anonymous Functions/Lambda.
XML files (with LINQ). Introduction to LINQ ( Language Integrated Query ) C#’s new LINQ capabilities allow you to write query expressions that retrieve.
LINQ Programming in C# LINQ CSE Prof. Roger Crawfis.
JSP Standard Tag Library
 Introduction  What is LINQ  Syntax  How to Query  Example Program.
Slides from Gang Luo, Xuting Zhao and Damien Guard
Extension Methods Programming in C# Extension Methods CSE Prof. Roger Crawfis.
LINQ, An IntroLINQ, An Intro Florin−Tudor Cristea, Microsoft Student Partner.
Eric Vogel Software Developer A.J. Boggs & Company.
Advanced .NET Programming I 13th Lecture
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 11 th Lecture Pavel Ježek
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# 3.0 and.NET 3.5: A Brief Overview Pavel Ježek.
Introduction to Databases A line manager asks, “If data unorganized is like matter unorganized and God created the heavens and earth in six days, how come.
Delegates and lambda functions Jim Warren, COMPSCI 280 S Enterprise Software Development.
Component 4/Unit 6f Topic VI: Create simple querying statements for the database The SELECT statement Clauses Functions Joins Subqueries Data manipulation.
Putting it all together: LINQ as an Example. The Problem: SQL in Code Programs often connect to database servers. Database servers only “speak” SQL. Programs.
Advanced C#, part IV Niels Hallenberg IT University of Copenhagen (With thanks to Peter Sestoft and Kasper Østerbye) BAAAP – Spring 2009.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Extension Methods, Anonymous Types LINQ Query Keywords, Lambda Expressions Based on material from Telerik Corporation.
Introduction to LINQ Lecture # 19 August Introduction How do you interrogate/manipulate data? What if you could do the work in a type-safe," string-free.
LINQ and C# 3.0 Mads Torgersen Program Manager for the C# Language Microsoft Corporation.
LINQ: It’s Not Your Father’s Data Access Denny Boynton Anheuser-Busch Companies.
The.NET Language Integrated Query Project Anders Hejlsberg TLN306 Technical Fellow Microsoft Corporation.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
JSTL Lec Umair©2006, All rights reserved JSTL (ni) Acronym of  JavaServer Pages Standard Tag Library JSTL (like JSP) is a specification, not an.
Neal Stublen How does XMLReader work?  XmlReader.Read() Advances to next node XmlReader properties access node name, value, attributes,
Hoang Anh Viet Hà Nội University of Technology Chapter 1. Introduction to C# Programming.
 Although VERY commonly used, arrays have limited capabilities  A List is similar to an array but provides additional functionality, such as dynamic.
Introduction to LINQ Chapter 11. Introduction Large amounts of data are often stored in a database—an organized collection of data. A database management.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Advanced C# Types Tom Roeder CS fa. From last time out parameters difference is that the callee is required to assign it before returning not the.
C#.Net Software Development Versions 1.0. Overview  Rational for Extension Methods  C# Specification for Extension Methods  Requirements for Extension.
C#: Future Directions in Language Innovation Anders Hejlsberg TLN307 Technical Fellow Microsoft Corporation.
Presented by Vishy Grandhi.  Architecture (Week 1) ◦ Development Environments ◦ Model driven architecture ◦ Licensing and configuration  AOT (Week 2)
Object Oriented Programming Generic Collections and LINQ Dr. Mike Spann
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 10 th Lecture Pavel Ježek
Inside LINQ to Objects How LINQ to Objects work Inside LINQ1.
JAVA BEANS JSP - Standard Tag Library (JSTL) JAVA Enterprise Edition.
PROGRAMMING IN C#. Collection Classes (C# Programming Guide) The.NET Framework provides specialized classes for data storage and retrieval. These classes.
Satisfy Your Technical Curiosity C# 3.0 Raj Pai Group Program Manager Microsoft Corporation
Linq Overview Vincent GERMAIN. Evolution - Rappel Langage  C# 2.0  C# 3.0 (Local type inference, Lambda expression, Method extension,Anonymous type)
IAP C# 2011 Lecture 2: Delegates, Lambdas, LINQ Geza Kovacs.
LINQ to DATABASE-2.  Creating the BooksDataContext  The code combines data from the three tables in the Books database and displays the relationships.
LINQ Language Integrated Query LINQ1. LINQ: Why and what? Problem Many data sources: Relational databases, XML, in-memory data structures, objects, etc.
LINQ and Lambda Expressions Telerik Software Academy LINQ Overview.
Chapter 11.  Large amounts of data are often stored in a database—an organized collection of data.  A database management system (DBMS) provides mechanisms.
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Part 1: Overview of LINQ Intro to LINQ Presenter: PhuongNQK.
Advanced .NET Programming I 6th Lecture
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
Language Integrated Query (LINQ)
Chapter 8 Advanced SQL.
Quiz Points 1 Rules Raise your hand if you know the question
LINQ - 2 Ravi Kumar C++/C# Team.
Advanced .NET Programming I 7th Lecture
Advanced .NET Programming I 6th Lecture
Chengyu Sun California State University, Los Angeles
CS4540 Special Topics in Web Development LINQ to Objects
Presentation transcript:

C# 3.0 Tom Roeder CS fa

Version 3 From PDC 2005 preview compiler available LINQ: language-integrated query High level points: adds native query functionality to C# adds better functional programming Several changes required to make this work implicitly typed variables extension methods

Implicitly typed variables var i = 5; var s = "Hello"; var d = 1.0; var orders = new Dictionary (); Type of the variable induced from expression must include initializer can’t be null. Why not? What happens if “var” is a class in scope? Works in for loops

Extension methods Can add methods to other classes any methods (although look static) only from static classes When import a namespace that has extensions, then added to classes once imported, called as usual Local methods take precedence first local for normal method, then extension

Extension methods public static class Extensions { public static int ToInt32(this string s) { return Int32.Parse(s); } public static T[] Slice (this T[] source, int index, int count) { if (index < 0 || count < 0 || source.Length – index < count) throw new ArgumentException(); T[] result = new T[count]; Array.Copy(source, index, result, 0, count); return result; } }

Extension methods using N1; namespace N1 { public static class E { public static void F(this object obj, int i) { } public static void F(this object obj, string s) { } } } class A { } class B { public void F(int i) { } } class C { public void F(object obj) { } }

Extension methods class X { static void Test(A a, B b, C c) { a.F(1); a.F("hello"); b.F(1); b.F("hello"); c.F(1); c.F("hello"); } }

Extension methods Not for properties, events, operators currently under consideration Equivalent to calling the static method difference from actually extending the class? How could we use this for Polynomials? Disadvantages? implicitness security

Lambda expressions Generalized function syntax x. x + 1 in C# 3.0, have x => x + 1 From anonymous delegate syntax: delegate(int x) { return x + 1;} Can have implicitly typed variables Can have more than one variable Can have expression or statement body NB: no statement bodies in preview compiler

Lambda expressions Can be converted to delegate type if parameters and body match delegate R Func (A arg); Func f1 = x => x + 1; Func f2 = x => x + 1; Func f3 = x => x + 1; Participate in type inference If expression body, get expression trees

Lambda expressions Type inference public static IEnumerable Select ( this IEnumerable source, Func selector) { foreach (T element in source) yield return selector(element); } If call Select(customers, c => c.Name); T, S mapped to appropriate types

Lambda expressions Given the code delegate R Func (A arg); static Z F (X value, Func f1, Func f2) { return f2(f1(value)); } what happens when get the following? F("1:15:30", s => TimeSpan.Parse(s), t => t.TotalSeconds)

Intializers Can initialize fields like attribute fields new C(1, 2, name=“my class”); works if public field or if property with set can be nested (eg. Rectangle with two Points) Collection initializers List digits = new List { 0, 1}; Must implement System.Generic.ICollection Object initializers var a = new Point { X = 0, Y = 1 };

Anonymous types var x = new {p1 = 10, p2 = “name”}; x is of anonymous type type can’t be referred to by name in program structural type equivalence two anonymous types can be compatible implicitly typed arrays var a = new[] { 1, 10, 100, 1000 }; must have consistent types or have implicit conversions

Query expressions Adds querying to language important for interaction with DB but also with built-in data structures leave query planning to data structure designer Implemented using above functionality anonymous types and variables useful lambda expressions make it cleaner.

Query expressions eg. var x = from s in students where s.City == “Ithaca" select s; defines an expression translates to invocation of Where method on students if select contains expression, calls Select uses lambda expressions as parameters we saw Select above

Other clauses groupby from c in customers group c.Name by c.Country c.GroupBy(c => c.Name, c => c.Country); orderby from c in customers orderby c.Name select new { c.Name, c.Phone } multiple from clauses from c in customers where c.City == "London" from o in c.Orders where o.OrderDate.Year == 2005 select new { c.Name, o.OrderID, o.Total }

Other clauses inner join? can be done with multiple generators just use a different object internally not as efficient? maybe need more syntax? don’t have full spec yet, just examples

Query expression pattern As with collections: not an interface just need to implement the methods necessary for backwards compatibility methods may be implemented by extension Methods named as above Any class that implements pattern can be accessed via the new syntax

Sequences A collection IEnumerable given iterator, can be viewed as a sequence New extension operators Take/TakeWhile Skip/SkipWhile Reverse Concat Intersect/Union/Except

Expression trees Data structure that represents expression type Expression if D is delegate type eg. Expression > e = x => x + 1; can be used to parse the function Spec not currently available Idea take an expression tree and convert to SQL

Database Integration Final step don’t think about the database types as separate allow databases to back classes! How would you do this in C#? Queries are now in the language eg. var x = from s in sources where s.fileName == “Polynomial.cs” select s;

DLinq Attributes [Table(Name="DVDTable")] public class DVD { [Column(Id = true)] public string Title; [Column] public string Rating; }

Connections Revisited public class MyDVDs : DataContext { public Table DVDs; public MyDVDs(string connection) : base(connection) {} } creates the connection to a database MyDVDs db = new MyDVDs(“dvd.mdf”); var x = from d in db.DVDs where d.Rating == “G” select d;

DLinq Query Expressions var x = the query is not executed immediately why not? Convert to Query holds the actual query as an Expression tree convert to SQL at execution time. When? eg. when need IEnumerator for foreach

Changes db.SubmitChanges() try to update the DB with our changes may fail: why? other applications may have made modifications what should we do? db.RejectChanges() throw away all changes since last updated Concurrency control optimistic in general

Transactions Transaction: unit of work isolated from other units can be made to look like happening serially using(TransactionScope ts = new TransactionScope()) { db.SubmitChanges(); ts.Complete(); } creates a new transaction for these updates if transaction succeeds, all changes accepted if transaction aborts, no object rollback

XLinq Instant XML intro language for defining markup nested tags and attributes eg Tom Roeder XML used as a document language often want to extract information from XML eg. in web search What is the relationship to DBs?

C# XML Programming Current model Read in XML document via various methods everything based in XMLDocument XLinq model XElement no document requirements: can be created anywhere can be queried as in DLinq built up functionally

XLinq Query Example from c in contacts.Elements("contact") where (string) c.Element("address").Element("state") == "WA" orderby (string) c.Element("name") select (string) c.Element("name"); What is the difference with DLinq? why all the casts? how to fix? LINQ team looking into schema support adds metadata to XML queries

C# 3.0 Conclusions query ability useful but many things are adding functional programming increases the possible styles of C# programming additions apparently not made on general principles but to support a particular narrow model of programming. Nonetheless: try it out