 Although VERY commonly used, arrays have limited capabilities  A List is similar to an array but provides additional functionality, such as dynamic.

Slides:



Advertisements
Similar presentations
Generics, Lists, Interfaces
Advertisements

Extension Methods, Anonymous Types LINQ Query Keywords, Lambda Expressions Svetlin Nakov Telerik Corporation
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
VBA Modules, Functions, Variables, and Constants
1 L41 Collections (1). 2 OBJECTIVES  What collections are.  To use class Arrays for array manipulations.  To use the collections framework (prepackaged.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
C# Programming: From Problem Analysis to Program Design1 Advanced Object-Oriented Programming Features C# Programming: From Problem Analysis to Program.
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.
Introduction to Classes and Objects CS-2303, C-Term Introduction to Classes and Objects CS-2303 System Programming Concepts (Slides include materials.
 2006 Pearson Education, Inc. All rights reserved Generics.
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
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.
Review of C++ Programming Part II Sheng-Fang Huang.
XML files (with LINQ). Introduction to LINQ ( Language Integrated Query ) C#’s new LINQ capabilities allow you to write query expressions that retrieve.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Lecture 9 Polymorphism Richard Gesick.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved. Note: C How to Program, Chapter 22 is a copy of C++ How to Program Chapter.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
You gotta be cool. Introduction to Classes, Objects and Strings Introduction Defining a Class with a Member Function Defining a Member Function with a.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Shipping Hub Application Introducing Generic Collections, LINQ, For Each...Next.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Java SE 8 for Programmers, Third Edition
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Learners Support Publications Classes and Objects.
Built-in Data Structures in Python An Introduction.
Introduction to LINQ Chapter 11. Introduction Large amounts of data are often stored in a database—an organized collection of data. A database management.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
Understanding Data Types and Collections Lesson 2.
Chapter 7: Characters, Strings, and the StringBuilder.
 All calls to method toString and earnings are resolved at execution time, based on the type of the object to which currentEmployee refers.  Known as.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
Chapter 4 Introduction to Classes, Objects, Methods and strings
CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX.
Internet & World Wide Web How to Program, 5/e. © by Pearson Education, Inc. All Rights Reserved. 2 Revised by Dr. T. Tran for CSI3140.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
Object Oriented Programming Generic Collections and LINQ Dr. Mike Spann
CSCI 3327 Visual Basic Chapter 8: Introduction to LINQ and Collections UTPA – Fall 2011.
CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections – Exercises 1 Xiang Lian The University of Texas – Pan American Edinburg,
Unit 6 Repetition Processing Instructor: Brent Presley.
CSCI-383 Object-Oriented Programming & Design Lecture 25.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
Arrays (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Overview of Previous Lesson(s) Over View VP is the methodology in which development allows the user to grab and use the desired tools like menus, buttons,
Chapter 18 Introduction to Custom Templates C++ How to Program, 9/e ©2016 by Pearson Education, Inc., Hoboken, NJ. All Rights Reserved. Instructor Note:
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
Object-Oriented Programming: Classes and Objects Chapter 1 1.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
Chapter 11.  Large amounts of data are often stored in a database—an organized collection of data.  A database management system (DBMS) provides mechanisms.
Lecture 8: Collections, Comparisons and Conversions. Svetla Boytcheva AUBG, Spring COS 240 Object-Oriented Languages.
Lecture 10 Collections Richard Gesick.
Introduction to LINQ and Generic Collections
Java Primer 1: Types, Classes and Operators
Chapter 14 Templates C++ How to Program, 8/e
Visual Basic 2010 How to Program
Tutorial 19 - Microwave Oven Application Building Your Own Classes and Objects Outline Test-Driving the Microwave Oven Application Designing.
Introduction to LINQ Chapter 11 10/28/2015 Lect 4 CT1411.
Introduction to LINQ Chapter 11.
Object Oriented Programming in java
Fundaments of Game Design
Presentation transcript:

 Although VERY commonly used, arrays have limited capabilities  A List is similar to an array but provides additional functionality, such as dynamic resizing.  A language called SQL is the international standard used to perform queries (i.e., to request information that satisfies given criteria) and to manipulate data.  C#’s new LINQ (Language-Integrated Query) capabilities allow you to write query expressions that retrieve information from a variety of data sources, not just databases.  LINQ to Objects can be used to filter arrays and List s, selecting elements that satisfy a set of conditions

 LINQ for different data sources:  A LINQ provider is a set of classes that implement LINQ operations and enable programs to interact with data sources to perform tasks such as projecting, sorting, grouping and filtering elements.

 set of features introduced in Visual Studio that extends powerful query capabilities to the language syntax of C# and Visual Basic.  LINQ introduces standard, easily-learned patterns for querying and updating data, and the technology can be extended to support potentially any kind of data store.  Visual Studio includes LINQ provider assemblies that enable the use of LINQ with ◦. NET Framework collections ◦ SQL Server databases ◦ ADO.NET Datasets (ActiveX Data Objects)ActiveX Data Objects ◦ XML documents  LINQ providers: blogs.msdn.com/charlie/archive/2006/10/05/Links-to-LINQ.aspxblogs.msdn.com/charlie/archive/2006/10/05/Links-to-LINQ.aspx  Examples:

 To find student who scored no less than 90 on the first test

Using Auto-implemented Properties Using Collection Initializer Using Object Initializer w/o explicit call to constructor or member access Nested

IEnumerable studentQuery = from student in students where student.Scores[0] > 90 select student; Same as var studentQuery = from student in students where student.Scores[0] > 90 select student;

 Beginning in Visual C# 3.0, declared at method scope can have an implicit type variables that are var (keyword).  An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.  The following two declarations of i are functionally equivalent: ◦ var i = 5; // implicitly typed (infer) int i = 5; //explicitly typed  Used for collections

 The where Clause  If the condition in the where clause evaluates to true, the element is selected —i.e., it’s included in the results. Here, the int s in the array are included only if they’re greater than 4. An expression that takes an element of a collection and returns true or false by testing a condition on that element is known as a predicate.  The select Clause  For each item in the data source, the select clause (line 22) determines what value appears in the results. In this case, it’s the int that the range variable currently represents. A LINQ query typically ends with a select clause. ◦ LINQ vs. Repetition Statements ◦ It would be simple to display the integers greater than 4 using a repetition statement that tests each value before displaying it. However, this would intertwine the code that selects elements and the code that displays them. With LINQ, these are kept separate, making the code easier to understand and maintain.

 The orderby Clause (line 32) sorts the query results in ascending order. ◦ Lines 43 and 56 use the descending modifier in the orderby clause to sort the results in descending order. ◦ An ascending modifier also exists but isn’t normally used, because it’s the default. ◦ Any value that can be compared with other values of the same type may be used with the orderby clause. A value of a simple type (e.g., int) can always be compared to another value of the same type.

 Software objects also communicate via interfaces.  A C# interface describes a set of methods that can be called on an object—to tell the object, for example, to perform some task or return some piece of information.  The IEnumerable interface describes the functionality of any object that can be iterated over and thus offers methods to access each element.  A class that implements an interface must define each method in the interface with a signature identical to the one in the interface definition. Implementing an interface is like signing a contract with the compiler.  Arrays are IEnumerable objects, so a foreach statement can iterate over an array’s elements. Similarly, each LINQ query returns an IEnumerable object.  Therefore, you can use a foreach statement to iterate over the results of any LINQ query. The notation indicates that the interface is a generic interface that can be used with any type of data (for example, int s, strings or Employees ).

 statement can iterate through the contents of arrays, collections and LINQ query results.  foreach iterates over IEnumerable object, which just happens to be what a LINQ query returns.  IEnumerable is an interface.  Interfaces define and standardize the ways in which people and systems can interact with one another. ◦ For example, the controls on a radio serve as an interface between radio users and the radio’s internal components. ◦ The controls allow users to perform a limited set of operations (e.g., changing the station, adjusting the volume, and choosing between AM and FM), and different radios may implement the controls in different ways (e.g., using push buttons, dials or voice commands). ◦ The interface specifies what operations a radio permits users to perform but does not specify how the operations are implemented. Similarly, the interface between a driver and a car with a manual transmission includes the steering wheel, the gear shift, the clutch, the gas pedal and the brake pedal. ◦ This same interface is found in nearly all manual-transmission cars, enabling someone who knows how to drive one manual-transmission car to drive another.

 Repetition statements that filter arrays focus on the steps required to get the results. This is called imperative programming.  LINQ queries, however, specify the conditions that selected elements must satisfy. This is known as declarative programming.  The System.Linq namespace contains the LINQ to Objects provider.

 You can declare a local variable and let the compiler infer the variable’s type based on the variable’s initializer. The var keyword is used in place of the variable’s type when declaring the variable.  A LINQ query begins with a from clause, which specifies a range variable ( value ) and the data source to query ( values ).  The range variable represents each item in the data source, much like the control variable in a foreach statement.  If the condition in the where clause evaluates to true, the element is selected.

 A predicate is an expression that takes an element of a collection and returns true or false by testing a condition on that element.  The select clause determines what value appears in the results.  The orderby clause sorts the query results in ascending order.  The descending modifier in the orderby clause sorts the results in descending order.  Any value that can be compared with other values of the same type may be used with the orderby clause.

 LINQ is not limited to querying arrays of simple types such as integers.  Comparable types in.NET are those that implement the IComparable.  All built-in types, such as string, int and double implement IComparable.  Figure 9.3 presents the Employee class. Figure 9.4 uses LINQ to query an array of Employee objects. 

decima l

 Any, First and Count Extension Methods  Any method (line 48) - returns true if there’s at least one element, and false if there are no elements.  The query result’s First method (line 49) returns the first element in the result. ◦ check that the query result is not empty (line 48) before calling First.  First and Any are not declared in the IEnumerable interface, but extension methods, but they can be used as if they were methods of IEnumerable.  LINQ defines many more extension methods, such as Count, which returns the number of elements in the results. ◦ Rather than using Any, we could have checked that Count was nonzero, but it’s more efficient to determine whether there’s at least one element than to count all the elements. ◦ The LINQ query syntax is actually transformed by the compiler into extension method calls, with the results of one method call used in the next. ◦ It’s this design that allows queries to be run on the results of previous queries, as it simply involves passing the result of a method call to another method.

 The select clause can be used to select a member of the range variable rather than the range variable itself.  The Distinct method removes duplicate elements, causing all elements in the result to be unique.

 The select clause can create a new object of anonymous type (a type with no name), which the compiler generates for you based on the properties listed in the curly braces ( {} ).  By default, the name of the property being selected is used as the property’s name in the result.  You can specify a different name for the property inside the anonymous type definition.

 new { e.FirstName, Last = e.LastName } (lines 65-66)  creates a new object of an anonymous type (a type with no name), which the compiler generates for you based on the properties listed in the curly braces ( {} ).  In this case, the anonymous type consists of properties for the first and last names of the selected Employee. The LastName property is assigned to the property Last in the select clause. This shows how you can specify a new name for the selected property. If you don’t specify a new name, the property’s original name is used—this is the case for FirstName in this example. .

 new { e.FirstName, Last = e.LastName } (lines 65-66)  The preceding query is an example of a projection—it performs a transformation on the data. In this case, the transformation creates new objects containing only the FirstName and Last properties. Transformations can also manipulate the data. For example, you could give all employees a 10% raise by multiplying their MonthlySalary properties by 1.1.  When creating a new anonymous type, you can select any number of properties by specifying them in a comma-separated list within the curly braces ({}) that delineate the anonymous type definition. In this example, the compiler automatically creates a new class having properties FirstName and Last, and the values are copied from the Employee objects. These selected properties can then be accessed when iterating over the results. Implicitly typed local variables allow you to use anonymous types because you do not have to explicitly state the type when declaring such variables.

 When the compiler creates an anonymous type, it automatically generates a ToString method that returns a string representation of the object. You can see this in the program’s output—it consists of the property names and their values, enclosed in braces.

 The.NET Framework Class Library provides several classes, called collections, used to store groups of related objects. These classes provide efficient methods that organize, store and retrieve your data without requiring knowledge of how the data is being stored. This reduces application-development time.  You’ve used arrays to store sequences of objects. Arrays do not automatically change their size at execution time to accommodate additional elements—you must do so manually by creating a new array or by using the Array class’s Resize method.  The collection class List (from namespace System.Collections.Generic ) provides a convenient solution to this problem. The T is a placeholder—when declaring a new List, replace it with the type of elements that you want the List to hold. This is similar to specifying the type when declaring an array. For example,  List list1;  declares list1 as a List collection that can store only int values, and  List list2

 List is called a generic class because it can be used with any type of object.  T is a placeholder for the type of the objects stored in the list.  Figure 9.5 shows some common methods and properties of class List.

 The Add method appends its argument to the end of the List.  The Insert method inserts a new element at the specified position.  The first argument is an index—as with arrays, collection indices start at zero.  The second argument is the value that’s to be inserted at the specified index.  The indices of elements at the specified index and above increase by one.

 The Count property returns the number of elements currently in the List.  List s can be indexed like arrays by placing the index in square brackets after the List variable’s name.  The Remove method is used to remove the first instance of an element with a specific value.  If no such element is in the List, Remove does nothing.  RemoveAt removes the element at the specified index; the indices of all elements above that index decrease by one.

 The Contains method returns true if the element is found in the List, and false otherwise.  Contains compares its argument to each element of the List in order, so using Contains on a large List is inefficient.  The Capacity property indicates how many items the List can hold without having to grow.  When the List grows, it must create a larger internal array and copy each element to the new array.  A List grows only when an element is added and there is no space for the new element.

 You can use LINQ to Objects to query Lists just as arrays.  In Fig. 9.7, a List of strings is converted to uppercase and searched for those that begin with "R".

 Line 21 uses LINQ’s let clause to create a new range variable. This is useful if you need to store a temporary result for use later in the LINQ query.  Typically, let declares a new range variable to which you assign the result of an expression that operates on the query’s original range variable. ◦ string method ToUpper converts each item to uppercase, then stores the result in the new range variable uppercaseString. ◦ use uppercaseString in the where, orderby and select clauses. The where clause (line 22) uses string method StartsWith to determine whether uppercaseString starts with the character "R". ◦ Method StartsWith performs a case-sensitive comparison to determine whether a string starts with the string received as an argument.  If uppercaseString starts with "R", method StartsWith returns true, and the element is included in the query results.

 The query is created only once (lines 20–24), yet iterating over the results (lines 27–28 and 36–37) gives two different lists of colors. This demonstrates LINQ’s deferred execution— the query executes only when you access the results — such as iterating over them or using the Count method—not when you define the query. This allows you to create a query once and execute it many times. Any changes to the data source are reflected in the results each time the query executes.  There may be times when you do not want this behavior, and want to retrieve a collection of the results immediately. LINQ provides extension methods ToArray and ToList for this purpose. These methods execute the query on which they’re called and give you the results as an array or List, respectively. These methods can also improve efficiency if you’ll be iterating over the results multiple times, as you execute the query only once.  C# has a feature called collection initializers, which provide a convenient syntax (similar to array initializers) for initializing a collection. For example, lines 12–16 of Fig. 9.7 could be replaced with the following statement: List items = new List { "aQua", "RusT", "yElLow", "rEd" };