Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: " Although VERY commonly used, arrays have limited capabilities  A List is similar to an array but provides additional functionality, such as dynamic."— Presentation transcript:

1

2

3  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

4  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.

5  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: http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811bhttp://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b

6

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

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

9 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;

10

11

12

13

14

15  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

16  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.

17  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.

18  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 ).

19  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.

20  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.

21  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.

22  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.

23  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.  https://www.youtube.com/watch?v=V-APRrWz_3o https://www.youtube.com/watch?v=V-APRrWz_3o

24

25 decima l

26

27

28

29

30

31  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.

32  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.

33  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.

34  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. .

35  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.

36  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.

37  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

38  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.

39

40

41

42

43  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.

44  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.

45  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.

46  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".

47

48

49  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.

50  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" };


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

Similar presentations


Ads by Google