Advanced Programming C# Lecture 10. dr inż. Małgorzata Janik

Similar documents
Visual C# 2012 How to Program by Pe ars on Ed uc ati on, Inc. All Ri ght s Re ser ve d.

Previous C# Releases. C# 3.0 Language Features. C# 3.0 Features. C# 3.0 Orcas. Local Variables. Language Integrated Query 3/23/2007

Advanced Programming C# Lecture 11 part 2. dr inż. Małgorzata Janik

Advanced Programming C# Lecture 12. dr inż. Małgorzata Janik

Steps of initialisation:

Querying In-Memory Data by Using Query Expressions

Introduction to LINQ. Paul Litwin Collaborative Data Services (CDS)

Functional programming in C#

LAB 1: LINQ PROJECT: UNIFIED LANGUAGE FEATURES FOR OBJECT AND RELATIONAL QUERIES...

Fall Semester (081) Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of Petroleum and Minerals

Advanced Programming C# Lecture 12. dr inż. Małgorzata Janik

Array Structure. In C#, arrays can be declared as fixed length or dynamic. A fixed length array can store a predefined number of items.

Chapter 6: Using Arrays

Advanced Programming C# Lecture 13. dr inż. Małgorzata Janik

LINQ Language-Integrated Query Introduction

Advances in Programming Languages

C# Programming in the.net Framework

Seminar 11 week 11 (11-15 December 2017)

Duhok Polytechnic University Amedi Technical Institute/ IT Dept. Halkawt Rajab Hussain

High Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd

By Jason Roberts. Foreword by Daniel Jebaraj

CHAPTER 1: INTRODUCING C# 3

Programming in C#

Object-Oriented Programming in C# (VS 2015)

Course Syllabus C # Course Title. Who should attend? Course Description

Concepts behind the C# 3 language. Faculty of Mathematics and Physics, Charles University in Prague

Putting it all together: LINQ as an Example

Object-Oriented Programming in C# (VS 2012)

Programming in C# with Microsoft Visual Studio 2010

Learning C# 3.0. Jesse Liberty and Brian MacDonald O'REILLY. Beijing Cambridge Farnham Köln Sebastopol Taipei Tokyo

Arrays: Higher Dimensional Arrays. CS0007: Introduction to Computer Programming

Course Hours

10266 Programming in C Sharp with Microsoft Visual Studio 2010

C# Fundamentals. Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh

PROGRAMMING IN VISUAL BASIC WITH MICROSOFT VISUAL STUDIO Course: 10550A; Duration: 5 Days; Instructor-led

C# Types. Industrial Programming. Value Types. Signed and Unsigned. Lecture 3: C# Fundamentals

DC69 C# &.NET DEC 2015

MCSA Universal Windows Platform. A Success Guide to Prepare- Programming in C# edusum.com

Industrial Programming

Computer Programming: C++

Variable Scope The Main() Function Struct Functions Overloading Functions Using Delegates Chapter 7: Debugging and Error Handling Debugging in Visual

Contents. LINQ for Visual C# 2008 i

"Charting the Course... MOC Programming in C# with Microsoft Visual Studio Course Summary

With examples in F# and C# SAMPLE CHAPTER. Tomas Petricek. WITH Jon Skeet FOREWORD BY MADS TORGERSEN MANNING

.NET Database Technologies. Entity Framework: Queries and Transactions

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

MSSQL and.net. Using SQL in.net, running.net code in SQL Server

Course Description. Audience. Module Title : 20483B: Programming in C# Duration : 5 days. Course Outline :: 20483B ::

LinQ Why we have to teach functional programmming

LINQ Queries. Getting Started.

CSC Web Programming. Introduction to SQL

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Programming in Visual Basic with Microsoft Visual Studio 2010

LINQ in Action. Fabrice Marguerie Steve Eichert Jim Wooley. Chapter 3. Copyright 2008 Manning Publications

Introduction to Programming Using Java (98-388)

NOTE: Answer ANY FOUR of the following 6 sections:

2/3/2018 CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II. Lecture Contents. C# basics. Methods Arrays. Dr. Amal Khalifa, Spr17

Computer Science & Engineering 150A Problem Solving Using Computers

INF 315E Introduction to Databases School of Information Fall 2015

Unit Assessment Guide

LINQ.NET LANGUAGE INTEGRATED QUERY. Dr. Victor Matos Cleveland State University April 2018

Course Outline. Introduction to java

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Types, lists & functions

Advanced Programming C# Lecture 5. dr inż. Małgorzata Janik

The course introduces many of the techniques and technologies employed by modern desktop and enterprise applications, including:

Grouping Objects. Primitive Arrays and Iteration. Produced by: Dr. Siobhán Drohan. Department of Computing and Mathematics

"Charting the Course to Your Success!" MOC B Programming in C# Course Summary

Final-Term Papers Solved MCQS with Reference

IMPLEMENTING THE LINQ QUERY LANGUAGE INTO THE C++ PROGRAMMING LANGUAGE USING A PREPROCESSOR

COPYRIGHTED MATERIAL. Contents. Part I: C# Fundamentals 1. Chapter 1: The.NET Framework 3. Chapter 2: Getting Started with Visual Studio

VALLIAMMAI ENGINEERING COLLEGE

EE221 Databases Practicals Manual

DOT NET COURSE BROCHURE

Microsoft Programming in C#

Arrays, Strings and Collections

Principles of Data Management

C# Programming: From Problem Analysis to Program Design. Fourth Edition

CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II

CS313D: ADVANCED PROGRAMMING LANGUAGE

Working with Objects. Overview. This chapter covers. ! Overview! Properties and Fields! Initialization! Constructors! Assignment

Programming in C# for Experienced Programmers

CS261: HOMEWORK 2 Due 04/13/2012, at 2pm

Programming Microsoft LINQ in

IN DEPTH THIRD EDITION. Jon Skeet FOREWORD BY ERIC LIPPERT MANNING

Oracle Database 11g: SQL and PL/SQL Fundamentals

COMP322 - Introduction to C++

Advanced Programming C# Lecture 2. dr inż. Małgorzata Janik

Microsoft Access 2016

Microsoft Access 2016

LINQ to SAP. Jürgen Bäurle. July Parago Media GmbH & Co. KG

The LINQ between XML and Database

C# and Java. C# and Java are both modern object-oriented languages

egrapher Language Reference Manual

Why do you want to know about functional programming?

C # Version 3.0 Specification

Fall 2017 CISC124 9/16/2017

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

An array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type.

Transcription:

Advanced Programming C# Lecture 10 dr inż. Małgorzata Janik majanik@if.pw.edu.pl Winter Semester 2017/2018

Project (part II)

Project part II Date: 18.12.2017 (next week!) Prepare the presentation that describes the project advancement since part I (max 5 min) Clear list of accomplished tasks Screenshots of application and/or code examples Working prototype expected (½ project should be finished) To-do list Send presentations to: majanik@if.pw.edu.pl before 18.12.2017, 10:00. 3 / 35

Classes #11: Project II The Final Mark is based on: PRESENTATION + clearly presented points from previous slide (2p) (reminder of the topic of the project, list of accomplished tasks, screenshots showing how the application works, to-do list) CODE + clarity of the code (comments, naming convention, etc..) (1p) + advancement of the project (since Part I) (4p) + working prototype (3p) = TOTAL 10 points 4 / 26

Arrays

Arrays Declaring an array, the square brackets ([]) must come after the type, not the identifier int[] table; // not int table[]; Size of the array is not part of its type int[] numbers; // declare numbers as an int array of any size numbers = new int[10]; // numbers is a 10-element array numbers = new int[20]; // now it's a 20-element array https://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx 6 / 35

Arrays declarations Single-dimensional arrays: Multidimensional arrays: string[,] names; Array-of-arrays (jagged): int[] numbers; byte[][] scores; Declaring them (as shown above) does not actually create the arrays. In C#, arrays are objects and must be instantiated. https://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx 7 / 35

Creation of arrays Single-dimensional arrays: Multidimensional arrays: int[] numbers = new int[5]; string[,] names = new string[5,4]; Array-of-arrays (jagged): byte[][] scores = new byte[5][]; for (int x = 0; x < scores.length; x++) { scores[x] = new byte[4]; } https://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx 8 / 35

Arrays Examples You can have a three-dimensional rectangular array: int[,,] buttons = new int[4,5,3]; You can even mix rectangular and jagged arrays. For example, the following code declares a single-dimensional array of threedimensional arrays of two-dimensional arrays of type int: int[][,,][,] numbers; https://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx 9 / 35

Initializing Arrays Single-Dimensional Array int[] numbers = new int[5] {1, 2, 3, 4, 5}; string[] names = new string[3] {"Matt", "Joanne", "Robert"}; You can omit the size of the array, like this: int[] numbers = new int[] {1, 2, 3, 4, 5}; string[] names = new string[] {"Matt", "Joanne", "Robert"}; You can also omit the new operator if an initializer is provided, like this: int[] numbers = {1, 2, 3, 4, 5}; string[] names = {"Matt", "Joanne", "Robert"}; https://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx 10 / 35

Initializing Arrays Multidimensional Array int[,] numbers = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} }; string[,] siblings = new string[2, 2] { {"Mike","Amy"}, {"Mary","Albert"} }; You can omit the size of the array, like this: int[,] numbers = new int[,] { {1, 2}, {3, 4}, {5, 6} }; string[,] siblings = new string[,] { {"Mike","Amy"}, {"Mary","Albert"} }; You can also omit the new operator if an initializer is provided, like this: int[,] numbers = { {1, 2}, {3, 4}, {5, 6} }; string[,] siblings = { {"Mike", "Amy"}, {"Mary", "Albert"} https://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx 11 / 35

Initializing Arrays Jagged Array (Array-of-Arrays) You can omit the size of the array, like this: int[][] numbers = new int[2][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} }; iint[][] numbers = new int[][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} }; You can also omit the new operator if an initializer is provided, like this: int[][] numbers = { new int[] {2,3,4}, new int[] {5,6,7,8,9} }; https://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx 12 / 35

Accessing Array Members Accessing array members is straightforward and similar to how you access array members in C/C++. int[] numbers = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; numbers[4] = 5; Multidimensional array and assigns 5 to the member located at [1, 1]: int[,] numbers = { {1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10} }; numbers[1, 1] = 5; Single-dimension jagged array: int[][] numbers = new int[][] { new int[] {1, 2}, new int[] {3, 4, 5}}; numbers[1][1] =https://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx 667; 13 / 35

Arrays are Objects Length: int[] numbers = {1, 2, 3, 4, 5}; int LengthOfNumbers = numbers.length; foreach on Arrays int[,] numbers = new int[3, 2] {{9, 99}, {3, 33}, {5, 55}}; foreach(int i in numbers) { Console.Write("{0} ", i); } The output of this example is: 9 99 3 33 5 55 https://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx 14 / 35

LINQ

LINQ LINQ Language Integrated Query (pronounced link ).NET Framework component that adds native data querying capabilities to.net languages LINQ extends the language by the addition of query expressions, which are similar to SQL statements can be used to conveniently extract and process data from arrays, enumerable classes, XML documents, relational databases, and third-party data sources. LINQ was released as a major part of.net Framework 3.5 on November 19, 2007. 16 / 35

LINQ Query All LINQ query operations consist of three distinct actions: Obtain the data source. Create the query. Execute the query. class IntroToLINQ { static void Main() { // The Three Parts of a LINQ Query: // 1. Data source. int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 }; // 2. Query creation. // numquery is an IEnumerable<int> var numquery = from num in numbers where (num % 2) == 0 select num; } } // 3. Query execution. foreach (int num in numquery) { Console.Write("{0,1} ", num); } In LINQ the execution of the query is distinct from the query itself; in other words you have not retrieved any data just by creating a query variable. 17 / 35

LINQ Data Sources The basic rule is very simple: a LINQ data source is any object that supports the generic IEnumerable<T> interface, or an interface that inherits from it (e.g. IQueryable<T>). Collections: Arrays & Lists string[] words = {"hello", "wonderful", "LINQ", "beautiful"}; XML documents // using System.Xml.Linq; XElement contacts = XElement.Load(@"c:\myContactList.xml"); Databases Northwnd db = new Northwnd(@"c:\northwnd.mdf"); // Query for customers in London. IQueryable<Customer> custquery = from cust in db.customers where cust.city == "London" select cust; More about IEnumerable interface: https://msdn.microsoft.com/en-us/library/9eekhta0.aspx 18 / 35

Type returned from LINQ query From previous example var type was used: we allow for the compiler to decide on the type Actual type of selecting several int numbers from the table would be collection IEnumerable<int> Similarly, for such query: var queryallcustomers = from cust in customers select cust; actual type would be IEnumerable<Customer> If we use queries such as Count or Max the result will be of type int. 19 / 35

Query Execution Deferred Execution query variable itself only stores the query commands. The actual execution of the query is deferred until you iterate over the query variable in a foreach statement. Forcing Immediate Execution Queries that perform aggregation functions over a range of source elements must first iterate over those elements. Examples of such queries are Count, Max, Average, and First. These execute without an explicit foreach statement because the query itself must use foreach in order to return a result. Note also that these types of queries return a single value, not an IEnumerable collection. To force immediate execution of any query and cache its results, you can call the ToList() or ToArray() methods. 20 / 35

Query Execution Deferred Execution Forcing Immediate Execution var evennumquery = (from num in numbers where (num % 2) == 0 select num).count(); foreach (int num in numquery) { Console.Write("{0,1} ", num); } List<int> numquery2 = (from num in numbers where (num % 2) == 0 select num).tolist(); var numquery3 = (from num in numbers where (num % 2) == 0 select num).toarray(); 21 / 35

LINQ Query All LINQ query operations consist of three distinct actions: Obtain the data source. Create the query. Execute the query. You can use any name you choose for the query as well as for the iterator. class IntroToLINQ { static void Main() { // The Three Parts of a LINQ Query: // 1. Data source. int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 }; // 2. Query creation. // numquery is an IEnumerable<int> var numquery = from num in numbers where (num % 2) == 0 select num; any name any name Good practice is to use a name that is easily readable by anybody. } } // 3. Query execution. foreach (int num in numquery) { Console.Write("{0,1} ", num); } In LINQ the execution of the query is distinct from the query itself; in other words you have not retrieved any data just by creating a query variable. 22 / 35

Task

Prerequisites Download School.cs class from: http://www.if.pw.edu.pl/~majanik/data/csharp/school.cs Create a Console Application In the beginning of the program create single School object. Use in as your collection. Complete next 8 tasks. Each task should be proceeded by //****** Task [put number] ******* comment 24 / 35

Task 0: arrays Create 1 dimenstional array for 10 integers. Fill it with random numbers 0-99. Print array on the screen. Write a LINQ query that will count number of all elements in the array. Write a LINQ query that will count number of even elements in the array. Write a LINQ query that will return list of odd elements in the array. Print results of all the queries. Create 2D array (10 x 5). Fill in with random numbers. Print it on the screen. 25 / 35

Filtering The most common query operation is to apply a filter in the form of a Boolean expression The filter causes the query to return only those elements for which the expression is true Example: var queryenglandcustomers = from cust in customers where cust.country == "England" select cust; You can combine multiple Boolean conditions in the where clause in order to further refine a query. The following code adds a condition so that the query returns those pupiles whose first mark was over 4 and whose last mark was less than 3.5. where pupil.marks[0] > 4 && pupil.marks[3] < 3.5 Task 1: write a LINQ query to extract all students in the school from Seattle or Warsaw. Print them on the screen. Write second query, that will count number of such students. Print the number on the screen. 26 / 35

Sorting Often it is convenient to sort the returned data. The orderby clause will cause the elements in the returned sequence to be sorted according to the default comparer Example: var queryenglandcustomersorder = from cust in customers where cust.city == "England" orderby cust.name ascending //descending select cust; Task 2: write a LINQ query to extract all students in the school from Seattle or Warsaw who are sorted by their last name. Print them on the screen. 27 / 35

Grouping The group clause enables you to group your results based on a key that you specify. Example: // querycustomersbycountry is an IEnumerable<IGrouping<string, Customer>> var querycustomersbycountry = from cust in customers group cust by cust.country; // customergroup is an IGrouping<string, Customer> foreach (var customergroup in querycustomersbycountry) { Console.WriteLine(customerGroup.Key); foreach (Customer customer in customergroup) { Console.WriteLine(" {0}", customer.name); } } Task 3: write a LINQ query that will write the names of the students (first & last) grouped by the city 28 / 35

Joining multiple inputs into one output.concat() You can use a LINQ query to create an output sequence that contains elements from more than one input sequence. The following example shows how to combine two in-memory data structures, but the same principles can be applied to combine data from XML or SQL or DataSet sources. Task 4: write a LINQ query that will return the collection all of students & teachers (last names only) that live in Warsaw. class Pet { public string Name { get; set; } public int Age { get; set; } } static Pet[] GetCats() { Pet[] cats = { new Pet { Name="Barley", Age=8 }, new Pet { Name="Boots", Age=4 } }; return cats; } static Pet[] GetDogs() { Pet[] dogs = { new Pet { Name="Bounder", Age=3 }, new Pet { Name="Snoopy", Age=14 }}; return dogs; } public static void ConcatEx1() { Pet[] cats = GetCats(); Pet[] dogs = GetDogs(); IEnumerable<string> query = (from cat in cats select cat.name).concat(from dog in dogs select dog.name); foreach (string name in query) { Console.WriteLine(name); } } // This code produces the following output: // Barley // Boots // Bounder // Snoopy 29 / 35

Selecting subset of each Source Element There are 2 primary ways to select a subset of each element in the source sequence: To select just one member of the source element, use the dot operation. To create elements that contain more than one property from the source element, you can use an object initializer with either a named object or an anonymous type. var query = from cust in Customers select cust.city; var query = from cust in Customer select new {Name = cust.name, City = cust.city}; Task 5: write a LINQ query that returns all students & teachers from Warsaw and creates anonymus type that includes both first & last names. 30 / 35

Lambda syntax Instead of from person in Data.People select person.lastname; we can write: Data.People.Select(p => p.lastname); Lambda syntax is more concise, however some operations (i.e. multiple table joins) is very complicated. There are a number of LINQ operations that only exist within the Lambda syntax: Single(), First(), Count() etc. SomeDataContext dc = new SomeDataContext(); var queue = from q in dc.sometable where q.somedate <= DateTime.Now && q.locked!= true orderby (q.priority, q.timecreated) select q; var queue2 = dc.sometable.where( q => q.somedate <= DateTime.Now && q.locked!= true ).OrderBy(q => q.priority).thenby(q => q.timecreated); Task 6: rewrite Task 1 & Task 4 with lambda syntax. 31 / 35

Transforming in-memory Objects into XML Task 7: try implementing example below to see how to create XML file from collection using LINQ. // Create the query. var studentstoxml = new XElement("Root", from student in students let x = String.Format("{0},{1},{2},{3}", student.scores[0], student.scores[1], student.scores[2], student.scores[3]) select new XElement("student", new XElement("First", student.first), new XElement("Last", student.last), new XElement("Scores", x) ) // end "student" ); // end "Root" // Execute the query. Console.WriteLine(studentsToXML); 32 / 35

Additional LINQ Quiz: http://www.albahari.com/nutshell/linqquiz.aspx LINQ Myths: http://www.albahari.com/nutshell/10linqmyths.aspx 33 / 35

References Getting Started with LINQ in C# https://msdn.microsoft.com/en-us/library/bb397933.aspx Introduction to LINQ Queries (C#) LINQ and Generic Types (C#) Basic LINQ Query Operations Data Transformations with LINQ (C#) Type Relationships in LINQ Query Operations Query Syntax and Method Syntax in LINQ C# Features That Support LINQ Walkthrough: Writing Queries in C# Step-by-step instructions for creating a C# LINQ project, adding a simple data source, and performing some basic query operations. C#: ZROZUMIEĆ LINQ http://itcraftsman.pl/zrozumiec-linq/ 34 / 35

THE END dr inż. Małgorzata Janik majanik@if.pw.edu.pl