2. When the app executes, another compiler (known as the just-in-time compiler
9.7 Deitel LINQ Resource Center
We’ve created a LINQ Resource Center (www.deitel.com/LINQ/) that contains many links to additional information, including blogs by Microsoft LINQ team members, books, sample chapters, FAQs, tutorials, videos, webcasts and more.
Summary
Section 9.1 Introduction
• .NET’s collection classes provide reusable data structures that are reliable, powerful and efficient.
• Lists automatically increase their size to accommodate additional elements.
• Large amounts of data are often stored in a database—an organized collection of data. Today’s most popular database systems are relational databases. SQL is the international standard lan- guage used almost universally with relational databases to perform queries (i.e., to request infor- mation that satisfies given criteria).
• LINQ allows you to write query expressions (similar to SQL queries) that retrieve information from a wide variety of data sources. You can query arrays andLists, selecting elements that satisfy a set of conditions—this is known as filtering.
• 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 sorting, grouping and filtering elements.
Section 9.2 Querying an Array ofintValues Using LINQ
• Repetition statements focus on the process of iterating through elements. LINQ specifies the conditions that selected elements must satisfy, not the steps necessary to get the results.
• TheSystem.Linqnamespace contains the classes for LINQ to Objects.
• Afromclause specifies a range variable and the data source to query. The range variable represents each item in the data source (one at a time), much like the control variable in aforeachstatement.
• If the condition in thewhereclause evaluates totruefor an element, it’s included in the results.
• Theselectclause determines what value appears in the results.
• A C# interface describes members that can be used to interact with an object.
• TheIEnumerable<T>interface describes the functionality of any object that’s capable of being iterated over and thus offers methods to access each element in some order.
• A class that implements an interface must define each member in the interface.
• Arrays and generic collections implement theIEnumerable<T>interface.
• Aforeachstatement can iterate over any object that implements theIEnumerable<T>orIEnu- merableinterface.
• A LINQ query returns an object that implements theIEnumerable<T>interface.
• Theorderbyclause sorts query results in ascending order by default. Results can also be sorted in descending order using thedescendingmodifier.
• C# provides implicitly typed local variables, which enable the compiler to infer a local variable’s type based on the variable’s initializer.
• To distinguish such an initialization from a simple assignment statement, thevarkeyword is used in place of the variable’s type.
• You can use local type inference with control variables in the header of afororforeachstatement.
• Implicitly typed local variables can be used to initialize arrays without explicitly giving their type.
To do so, usenew[]to specify that the variable is an array.
Section 9.3 Querying an Array ofEmployeeObjects Using LINQ
• LINQ can be used with collections of most data types.
• Anybooleanexpression can be used in awhereclause.
• Anorderbyclause can sort the results according to multiple properties specified in a comma-sep- arated list.
• MethodAnyreturnstrueif there’s at least one element in the result; otherwise, it returnsfalse.
• TheFirstmethod returns the first element in the query result. You should check that the query result is not empty before callingFirst.
• TheCountmethod returns the number of elements in the query result.
• TheDistinctmethod removes duplicate values from query results.
• You can select any number of properties (a projection) in aselectclause by specifying them in a comma-separated list in braces after thenewkeyword. The compiler automatically creates a new class having these properties—called an anonymous type.
Section 9.4 Introduction to Collections
• The .NET collection classes provide efficient methods that organize, store and retrieve data with- out requiring knowledge of how the data is being stored.
• ClassList<T>is similar to an array but provides richer functionality, such as dynamic resizing.
• TheAddmethod appends an element to the end of aList.
• TheInsertmethod inserts a new element at a specified position in theList.
• TheCountproperty returns the number of elements currently in aList.
• Lists can be indexed like arrays by placing the index in square brackets after theListobject’s name.
Terminology 369
• TheRemovemethod is used to remove the first element with a specific value.
• TheRemoveAtmethod removes the element at the specified index.
• TheContainsmethod returnstrueif the element is found in theList, andfalseotherwise.
• TheCapacityproperty indicates how many items aListcan hold without growing.
Section 9.5 Querying a Generic Collection Using LINQ
• LINQ to Objects can queryLists.
• LINQ’sletclause creates a new range variable. This is useful if you need to store a temporary result for use later in the LINQ query.
• TheStartsWithmethod of thestringclass determines whether astringstarts with thestring passed to it as an argument.
• A LINQ query uses deferred execution—it executes only when you access the results, not when you create the query.
Terminology
Addmethod of classList<T>
anonymous type
Anyextension method forIEnumerable<T>
ascendingmodifier of theorderbyclause
Capacityproperty of classList<T>
collection initializer
Containsmethod of classList<T>
Countextension method forIEnumerable<T>
Countproperty of classList<T>
declarative programming deferred execution
descendingmodifier of theorderbyclause
Distinctextension method forIEnumerable<T>
dynamic resizing
filtering a collection with LINQ
Firstextension method forIEnumerable<T>
fromclause of a LINQ query
IEnumerable<T>interface imperative programming implicitly typed local variable
Insertmethod of classList<T>
interface
letclause of a LINQ query LINQ (Language Integrated Query) LINQ provider
LINQ to Objects
List<T>collection class
orderbyclause of a LINQ query predicate
projection query expression query using LINQ range variable
Removemethod of classList<T>
RemoveAtmethod of classList<T>
selectclause of a LINQ query
StartsWithmethod of classstring
ToUppermethod of classstring
varkeyword
whereclause of a LINQ query
Self-Review Exercises
9.1 Fill in the blanks in each of the following statements:
a) Use the property of theListclass to find the number of elements in theList. b) The LINQ clause is used for filtering.
c) are classes specifically designed to store groups of objects and provide methods that organize, store and retrieve those objects.
d) To add an element to the end of aList, use the method.
e) To get only unique results from a LINQ query, use the method.
9.2 State whether each of the following istrueorfalse. Iffalse, explain why.
a) Theorderbyclause in a LINQ query can sort only in ascending order.
b) LINQ queries can be used on both arrays and collections.
c) TheRemovemethod of theListclass removes an element at a specific index.
Answers to Self-Review Exercises
9.1 a)Count. b)where. c) Collections. d)Add. e)Distinct.
9.2 a) False. The descending modifier is used to make orderby sort in descending order.
b) True. c) False.Removeremoves the first element equal to its argument.RemoveAtremoves the el- ement at a specific index.
Exercises
9.3 (Querying an Array ofInvoiceObjects)Use the classInvoiceprovided in theex09_03fold- er with this chapter’s examples to create an array ofInvoiceobjects. Use the sample data shown in Fig. 9.8. ClassInvoiceincludes four properties—aPartNumber(typeint), aPartDescription(type
string), aQuantityof the item being purchased (typeint) and aPrice(typedecimal). Perform the following queries on the array ofInvoiceobjects and display the results:
a) Use LINQ to sort theInvoiceobjects byPartDescription. b) Use LINQ to sort theInvoiceobjects byPrice.
c) Use LINQ to select thePartDescriptionandQuantityand sort the results byQuantity. d) Use LINQ to select from eachInvoicethePartDescriptionand the value of theIn-
voice(i.e.,Quantity * Price). Name the calculated columnInvoiceTotal. Order the results byInvoicevalue. [Hint:Useletto store the result ofQuantity * Pricein a new range variabletotal.]
e) Using the results of the LINQ query inPart d, select theInvoiceTotals in the range
$200 to $500.
9.4 (Duplicate Word Removal)Write a console app that inputs a sentence from the user (as- sume no punctuation), then determines and displays the nonduplicate words in alphabetical order.
Treat uppercase and lowercase letters the same. [Hint:You can usestringmethodSplitwith no arguments, as insentence.Split(), to break a sentence into an array ofstrings containing the in- dividual words. By default,Splituses spaces as delimiters. UsestringmethodToLowerin these-
lectandorderbyclauses of your LINQ query to obtain the lowercase version of each word.]
9.5 (Sorting Letters and Removing Duplicates)Write a console app that inserts 30 random let- ters into aList< char >. Perform the following queries on theListand display your results: [Hint:
Strings can be indexed like arrays to access a character at a specific index.]
a) Use LINQ to sort theListin ascending order.
b) Use LINQ to sort theListin descending order.
c) Display theListin ascending order with duplicates removed.
Part number Part description Quantity Price
83 Electric sander 7 57.98
24 Power saw 18 99.99
7 Sledge hammer 11 21.50
77 Hammer 76 11.99
39 Lawn mower 3 79.50
68 Screwdriver 106 6.99
56 Jig saw 21 11.00
3 Wrench 34 7.50
Fig. 9.8 | Sample data for Exercise 9.3.
10
Classes and Objects:
A Deeper Look
But what, to serve our private ends, Forbids the cheating of our friends?
—Charles Churchill
This above all: to thine own self be true.
—William Shakespeare.
O b j e c t i v e s
In this chapter you’ll:
I Understand encapsulation and data hiding.
I Use composition to allow a class to have references to objects of other classes as members.
I Throw an exception to indicate that an argument is out of range.
I Use keywordthis.
I Usestaticvariables and methods.
I Usereadonlyfields.
I Take advantage of C#’s memory-management features.
I Use the IDE’sClass View andObject Browser windows.
I Use object initializers to create an object and initialize it in the same statement.