Introduction to LINQ and Collections
200 likes | 224 Vues
Learn the basic concept of LINQ, how to use LINQ to query an array, how to sort an array using LINQ, and how to manipulate collections using LINQ.
Introduction to LINQ and Collections
E N D
Presentation Transcript
CSCI 3327 Visual Basic Chapter 8: Introduction to LINQ and 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
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
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…EachNext) • 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 OrderBy value Select value default: Ascending
Querying an Array of Primitive-Type Elements Using LINQ (cont'd) • Dim sorted = From value In filtered OrderBy value Descending Select value • Dim sorted = From value In values Where (value > 4) OrderBy value Descending Select value
Example 11.2: LINQWithArrayOfIntegers.vb • URL: • http://media.pearsoncmg.com/ph/esm/deitel/vb_htp_2010/codeexamples.html • Keywords in LINQ • From … In • Where • Select • Order By … Descending • Chained vs. one query
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_htp_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_htp_2010/codeexamples.html • String • Color.StartsWith("r") • Color.ToUpper() • The changes to the data source will be included when we re-execute the query
Introduction to Collections • .NET framework class library provides several classes called collections • The collection class List (OFT) comes from namespace System.Collections.Generic • The T is the placeholder change as appropriate as: • Dim list1 As List (OFInteger)
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 • DimstartswithR = Fromitem Initems Whereitem.StartsWith(“r”) OrderByitem Selectitem.ToUpper() ForEachitem InstartswithR 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() AsString = Split(txtEnterGrade.Text, " ") • Now let us create our own array instead of using grades() which is an array of string Dim scores(80) AsInteger For i = 0 To grades.GetUpperBound(0) scores(i) = Val(grades(i)) total += scores(i) lstBoxGrades.Items.Add(scores(i)) Next