You are on page 1of 31
Addison Wesley is an imprint of © 2011 Pearson Addison-Wesley. All rights reserved. Slide 1

Addison Wesley

is an imprint of

Addison Wesley is an imprint of © 2011 Pearson Addison-Wesley. All rights reserved. Slide 1

© 2011 Pearson Addison-Wesley. All rights reserved.

Addison Wesley is an imprint of © 2011 Pearson Addison-Wesley. All rights reserved. Slide 1

Slide 1

Chapter 3 Collections Updated: 3/22/2011 © 2011 Pearson Addison-Wesley. All rights reserved. Slide 2

Chapter 3

Collections

Updated: 3/22/2011

Contents

Contents • 3.1 ArrayLists • 3.2 ArrayLists of Custom Objects • 3.3 List and Dictionary Classes

3.1 ArrayLists 3.2 ArrayLists of Custom Objects 3.3 List and Dictionary Classes 3.4 Language Integrated Query (LINQ)

Types of Collections

Types of Collections • A collection is any sequenced or unsequenced group of values • A

A collection is any sequenced or unsequenced group of values

A list is a collection in which the values retain their relative positions

a list of steps to solve a problem

A set has no ordering

set of people with green eyes

A dictionary is a collection that associates keys with corresponding values

a dictionary of Student IDs and transcripts

ArrayList Class

ArrayList Class • Items are in order, like an array • Additional features: − expands as

Items are in order, like an array

Additional features:

expands as new items are inserted has methods to find, insert, and remove items may contain different types of objects

ArrayList Class • Items are in order, like an array • Additional features: − expands as

ArrayList Methods and Properties

ArrayList Methods and Properties © 2011 Pearson Addison-Wesley. All rights reserved. Slide 6
ArrayList Methods and Properties © 2011 Pearson Addison-Wesley. All rights reserved. Slide 6

ArrayList Operations

ArrayList Operations • Creating an ArrayList Dim customers As New ArrayList • Adding and Inserting Items

Creating an ArrayList

Dim customers As New ArrayList

Adding and Inserting Items

customers.Add("Baker") customers.Add(1, "Ramirez")

Removing Items

customers.RemoveAt(1)

customers.Remove("Baker")

More ArrayList Operations

More ArrayList Operations • Contains method Dim found As Boolean found = customers.Contains("Baker") • IndexOf method

Contains method

Dim found As Boolean found = customers.Contains("Baker")

IndexOf method

Dim index As Integer = customers.IndexOf("Baker")

If index = -1 Then

lblStatus.Text = "Customer not found" End If

More ArrayList Operations

Item property

More ArrayList Operations • Item property Dim name As String = CStr(customers.Item(2)) customers.Item(2) = "Johnson" •

Dim name As String = CStr(customers.Item(2)) customers.Item(2) = "Johnson"

IndexOutOfRangeException

thrown when index does not point to an item

Tutorial 3-1

Tutorial 3-1 • Student class contains an ArrayList of test scores. • User can add students,

Student class contains an ArrayList of test scores.

User can add students, scores, and view the

average.

Tutorial 3-1 • Student class contains an ArrayList of test scores. • User can add students,
  • 3.2 ArrayLists of Custom Objects

3.2 ArrayLists of Custom Objects • Define a class for the items that will be inserted

Define a class for the items that will be inserted in

the list

Always create a new instance of the class before inserting a new item

If you plan to sort the ArrayList, your class must implement the CompareTo method

If you plan to search the ArrayList, your class must implement the Equals method

CompareTo

CompareTo • Standard format: Function CompareTo(ByVal obj As Object) As Integer • Comparing two objects: Dim

Standard format:

Function CompareTo(ByVal obj As Object) As Integer

Comparing two objects:

Dim result As Integer = A.CompareTo(B)

Return value:

If A is less than B, A.CompareTo(B) returns a negative integer.

If A is equal to B, A.CompareTo(B) returns zero.

If A is greater than B, A.CompareTo(B) returns a positive nonzero integer.

IComparable Interface

IComparable Interface • CompareTo implements this interface • Definition: © 2011 Pearson Addison-Wesley. All rights reserved.

CompareTo implements this interface

Definition:

IComparable Interface • CompareTo implements this interface • Definition: © 2011 Pearson Addison-Wesley. All rights reserved.

Student Example

1: Class Student

Student Example 1: Class Student 2: Implements IComparable 3: Public Property Id As String 4: Public

2:

Implements IComparable

3:

Public Property Id As String

4:

Public Property LastName As String

5:

Public Sub New(ByVal pId As String, ByVal pName As String)

6:

Id = pId

7:

LastName = pName

8:

End Sub

9:

10:

Public Function CompareTo(ByVal obj As Object) As Integer _

11:

Implements IComparable.CompareTo

12:

Dim S As Student = CType(obj, Student)

13:

Return Me.Id.CompareTo(S.Id)

14:

End Function

15: End Class

© 2011 Pearson Addison-Wesley. All rights reserved.

Equals Method

Equals Method • Implement in your custom classes to provide a basis for comparing objects •

Implement in your custom classes to provide a basis

for comparing objects

Standard format:

Public Overrides Function Equals(ByVal obj As Object) As Boolean

Return Me.field.Equals(CType(obj, Student).field)

End Function

Where field is the name of a class field.

Tutorial 3-2

Tutorial 3-2 • Builds an ArrayList of Student objects • Shows how to implement the Equals

Builds an ArrayList of Student objects

Shows how to implement the Equals method.

Tutorial 3-2 • Builds an ArrayList of Student objects • Shows how to implement the Equals
  • 3.3 List and Dictionary Classes

3.3 List and Dictionary Classes • ArrayList does not limit the types of items that are

ArrayList does not limit the types of items that are

inserted

Can lead to runtime error (Invalid cast)

A strongly typed collection can only contain a single type of object*

Generic classes

Take on specific data type when instances of the class are created

* Including classes related by inheritance

System.Collections.Generic

System.Collections.Generic • This .NET Namespace contains • List( Of Type ) • Dictionary( Of KeyType, ValueType

This .NET Namespace contains

List( Of Type )

Dictionary( Of KeyType, ValueType )

SortedDictionary( Of KeyType, ValueType )

KeyValuePair( Of KeyType, ValueType )

List( Of Type )

List( Of Type ) • Strongly typed sequential collection of items • Nearly identical properties and

Strongly typed sequential collection of items

Nearly identical properties and methods as the

ArrayList class Enforces strict type checking

Example:

Dim intList As New List(Of Integer)

intList.Add(30)

intList.Add(10)

intList.Add(20)

Dictionary

Dictionary • Dictionary( Of KeyType , ValueType ) • Maps a set of keys to a

Dictionary( Of KeyType, ValueType )

Maps a set of keys to a set of values

each key in the dictionary has a single value associated with that key

Keys must be unique, but not the values

keys must implement IComparable, as well as the Equals method

Optimized for fast searching (of the keys)

Dictionary

Dictionary • Creating a Dictionary: Dim salaries As New Dictionary(Of Integer, Decimal) • Adding items: salaries.Add(3001,

Creating a Dictionary:

Dim salaries As New Dictionary(Of Integer, Decimal)

Adding items:

salaries.Add(3001, 50000D) salaries.Add(2020, 45000D)

Looping through the items:

For Each entry In salaries lstBox.Items.Add(entry.Key & "-->" & entry.Value) Next

Tutorial 3-3

Tutorial 3-3 • Creating a text concordance • Reads a file, creates a catalog of all

Creating a text concordance

Reads a file, creates a catalog of all words found in the file.

The words are inserted as keys into a dictionary

each entry contains a list of line numbers where the word is found

Tutorial 3-3 • Creating a text concordance • Reads a file, creates a catalog of all
  • 3.4 Language Integrated Query

3.4 Language Integrated Query • Also known as LINQ • A query language in .NET that

Also known as LINQ

A query language in .NET that can display and

update information from different types of data sources:

lists in memory databases XML files Excel spreadsheets

LINQ for Objects deals exclusively with objects residing in memory

LINQ Clauses

LINQ Clauses • Four basic clauses used in queries • From — Identifies the data source,

Four basic clauses used in queries

FromIdentifies the data source, which can be an object such as an array or List

Where (optional)Holds a Boolean expression that selects which values will be copied from the data

source

SelectIdentifies the name of the field(s) that will be returned by the query

Order By (optional)Indicates how the results of the query will be ordered

Array Example

Array Example Dim intNumbers() As Integer = {4, 104, 2, 102, 1, 101, 3, 103} Query

Dim intNumbers() As Integer = {4, 104, 2, 102, 1, 101, 3,

103}

Query returns all array values that are greater than 100,

sorted in ascending order:

Dim query = From item In intNumbers

Where item > 100

Select item Order by item

© 2011 Pearson Addison-Wesley. All rights reserved.

Query a List of Objects

Public Class Student Public Property Id As String

Query a List of Objects Public Class Student Public Property Id As String Public Property LastName

Public Property LastName As String Public Property Status As Integer 'values: 1,2,3,4 Public Property Gpa As Double 'grade point average Public Property Major As String

End Class

Select all students and sort by ID number:

Dim query = From aStudent In studentList

Select aStudent

Order by aStudent.Id

© 2011 Pearson Addison-Wesley. All rights reserved.

Assigning to a Grid

Assigning to a Grid Select all students, sort by major, display the major and last name,

Select all students, sort by major, display the major and last name, and assign the output to a DataGridView control:

Dim query = From aStudent In studentList Select aStudent.Major, aStudent.LastName Order By Major dgvStudents.DataSource

= query.ToList()

Assigning to a Grid Select all students, sort by major, display the major and last name,

© 2011 Pearson Addison-Wesley. All rights reserved.

Tutorial 3-4

Tutorial 3-4 • Performing LINQ queries on a list. Displays, sorts, filters, and calculates statistics on

Performing LINQ queries on a list. Displays, sorts,

filters, and calculates statistics on a list of students

Tutorial 3-4 • Performing LINQ queries on a list. Displays, sorts, filters, and calculates statistics on

Querying a Dictionary

Querying a Dictionary • Each entry is a KeyValuePair, with the following properties: − Key, Value

Each entry is a KeyValuePair, with the following properties:

Key, Value

Dim studentColl As New Dictionary(Of Integer, Student) With studentColl .Add(1241, New Student(''1241'', ''Jones'', 1, 3.2, ''BIO''))Dim query = From aPair In studentColl 'etc. End With

' Query:

Select aPair.Value Order By Value.Id

Key Terms

Key Terms • anonymous types • ArrayList class • collection • comparator • CompareTo method •

anonymous types

ArrayList class

collection

comparator

CompareTo method

Dictionary(Of KeyType,

ValueType)

extension method

generic class

IComparable interface

interface

KeyValuePair

Language Integrated Query (LINQ)

LINQ for objects list List(Of Type) map method signature override the Equals method SortedDictionary strongly typed collection type inference weakly typed collection

The End © 2011 Pearson Addison-Wesley. All rights reserved. Slide 31

The End