csci 3327 visual basic chapter 8: introduction to linq and collections utpa – fall 2011
TRANSCRIPT
CSCI 3327 Visual Basic CSCI 3327 Visual Basic Chapter 8: Introduction to LINQ Chapter 8: Introduction to LINQ
and Collectionsand Collections
UTPA – Fall 2011
Objectives
• In this chapter, you will:– Become familiar with the basic concept of LINQ– Learn how to use LINQ to query an array– Learn how to sort an array using LINQ– Learn how to manipulate collections (e.g., List) by
LINQ
2
LINQ
• Language Integrated Query (LINQ)• Old way:
– Structured Query Language (SQL)– Queries are written in string and passed to database
which interprets the string, processes the request, and returns the results
• LINQ allows a programming language to submit queries directly to a wide range of data sources (not just databases!)
LINQ (cont'd)
• LINQ is a logical extension of querying and manipulating data in databases
• Data sources– Arrays– Collections
• Items collection of a ListBox
– Files
• Query expression is similar to SQL
4
Writing an LINQ Query
• A LINQ query begins with a From clause– After From clause, specify a range variable and the
data source to query– The range variable represents each item in the data
source (much like For…Each Next)
• The Where clause evaluates to True or False – If True, the value is selected
• The Select clause determines what value appears in the results
Querying an Array of Primitive-Type Elements Using LINQ
• Dim filtered = From value In values
Where value > 4
Select value
• Dim sorted = From value In filtered
Order By value
Select value default: Ascending
Querying an Array of Primitive-Type Elements Using LINQ (cont'd)
• Dim sorted = From value In filtered
Order By value Descending
Select value
• Dim sorted = From value In values
Where (value > 4)
Order By value Descending
Select value
Example 11.2: LINQWithArrayOfIntegers.vb
• URL:– http://media.pearsoncmg.com/ph/esm/deitel/vb_ht
p_2010/codeexamples.html
• Keywords in LINQ– From … In– Where– Select– Order By … Descending
• Chained vs. one query
8
LINQ Providers
• LINQ provider is a layer between the LINQ engine and the data source
• It consists of a set of classes that implement operation needed by LINQ – Generic methods allow to display variables of
various types with a single method– E.g., counting, accessing, comparing, and
removing elements
Example 11.3-11.4: LINQWithEmployeeArray.vb
• URL:– http://media.pearsoncmg.com/ph/esm/deitel/vb_ht
p_2010/codeexamples.html
• nameSorted.Count()• nameSorted.First()• Keyword: Distinct• Anonymous types
– The new class that does not have a name and cannot be used to create new objects
Other IEnumerable Extension Methods
• Any
• Average
• Cast
• Contains
• Count
• Distinct
• ElementAt
• First
• Last
• Max
• Min
• Reverse
• Sum
Example 11.7: DeferredExecution.vb
• URL:– http://media.pearsoncmg.com/ph/esm/deitel/vb_ht
p_2010/codeexamples.html
• String – Color.StartsWith("r")– Color.ToUpper()
• The changes to the data source will be included when we re-execute the query
12
Introduction to Collections
• .NET framework class library provides several classes called collections
• The collection class List (OF T) comes from namespace System.Collections.Generic– The T is the placeholder change as appropriate as:– Dim list1 As List (OF Integer)
Problems With Arrays
• Must specify size of array
• Only some languages allow redimesioning it at runtime
• .NET framework’s collection class overcomes this limitation
• We are going to use the List class from this collection
List Class
• Lists are similar to arrays but provide additional functionality:– Dynamic resizing– Provides many built-in methods– Can use LINQ queries
Property or Method of List
• Add (to the end)• Capacity (how many)• Clear (remove all)• Contains(returns true or false)• Count (how many)• Indexof (first occurrence of specified value in list)• Insert (add at specified index)• trimExcess
Example
• Dim items as new List(OF String)
• Items.Add(“red”)
• Items.Insert(0,”yellow”)
Querying a Generic Collection
• Dim startswithR = From item In items Where item.StartsWith(“r”)
Order By item Select item.ToUpper()
For Each item In startswithR Console.Write(item)
Next• Displays all items starts with r, but all in uppercase
STD DEV Program in Your Assignment
• Reading the grades from a string Dim grades() As String = Split(txtEnterGrade.Text, " ")• Now let us create our own array instead of using grades()
which is an array of string Dim scores(80) As Integer For i = 0 To grades.GetUpperBound(0) scores(i) = Val(grades(i)) total += scores(i) lstBoxGrades.Items.Add(scores(i)) Next
20