Bài giảng Lập trình C# 2010: Chương 4 trình bày về Using Arrays and Collections (Sử dụng mảng và Bộ sưu tập) như khái niệm, đặc điểm, cú pháp, thao tác thực hiện và các nội dung khác.
Trang 2One Dimension Array
Trang 35 2 9 7 6 0 8
M[0] M[1] M[2] M[3] M[4] M[5] M[6]
- Same name
- Same type
- Get Element by Index ( 0 n-1)
One Dimension Array
Trang 4• Programmer specifies the type of the elements
of the array
• new operator to allocate dynamically the
number of elements in the array
• Array declarations and initializations need not
be in the same statement
• In arrays of value types, each element contains
one value of the declared type
Declaring & Creating Arrays
Trang 6int M1 [] =new int [ 10 ] ;
Trang 7• array_name Length: return size of array
object at position index.
position index.
• array_name SetValue ( object value, int index):
add or modify an object at position index
object at position index
Properties & Methods
Trang 8Passing Arrays to Method
• Pass arrays as arguments to methods by specifying the name of the array (no
brackets)
• Arrays are passed by reference
• Individual array elements are passed by
value
Trang 9static void inputA rray(int[] arr)
{
Random ran = new Random ();
for ( int i = 0; i < arr.Length; i+ + )
arr[i] = ran.N ext(100);
}
Passing Arrays to Method
Trang 10Using out or ref keyword to pass by reference
static void edit( out int n)
Trang 11The out parameter must be assigned to before control leaves the current method
static void edit(out int n)
{
//n = -113;
}
Compile error
Trang 12edit( out arr[0]);
Tw o w ays: arr[0] -113
arr[0]= 100;
Trang 13Multi Dimension
7 2 9
9 5 4
8 0 3
0 1 6
Trang 15arrName = new DataType [ rowSize , colSize ];
DataType [ , ] arrName =
new DataType [ rowSize , colSize ];
int[,] M = new int[2, 2];
M [0, 0] = 1; M [0, 1] = 2;
M [1, 0] = 5; M [1, 1] = 3;
int[,] M = { {1,8} , {2,5} };
Trang 16G etLength(int dim ension)
int[,] M = {{1,8},{2,5},{1,1} };
row = M G etLength(0); row = 3
col= M G etLength(1); col= 2
int[, ,] M 2 = new Int32[3, 4, 5];
Trang 17for ( int i = 0; i < M G etLength(0); i+ + )
Trang 18Arrays of Arrays
When we want to create a multi Array with
different size:
- The first, we declare size of row, so each
row will hold an array with any size
- The second, We will declare those array
- And Initialize value for each item in array
DataType[ ][ ] arrName = new DataType[Size][ ];
Trang 19int [][] K = new int [3][];
Trang 20Array Class
Provides methods for creating, manipulating, searching, and sorting arrays, thereby serving as the base class for all arrays in the common language runtime.
Trang 21CreateInstance(Type, Int32 [])
Creates a multidimensional Array of the
specified Type and dimension lengths, with
zero-based indexing The dimension lengths
are specified in an array of 32-bit integers
Trang 22// Creates and initializes a new tw
o-dim ensional Array of type Int32.
(2 row s, 3 cols)
Array m yArr =
Array C reateInstance( typeof ( Int32 ),2, 3);
i < = m yArr.G etU pperBound(0); i+ + )
j < = m yArr.G etU pperBound(1); j+ + )
{
m yArr.SetValue(i+ j, i, j);
}
Trang 23for ( int i = m yArr.G etLow erBound(0);
i < = m yArr.G etU pperBound(0); i+ + )
{
for ( int j =
m yArr.G etLow erBound(1);
j < = m yArr.G etU pperBound(1); j+ + )
Trang 24Method Description
Copy(Array,
Array, Int32) Copies a range of elements from an Array starting at the
first element and pastes them into another Array starting at the first element The length is specified as a 32-bit integer
Trang 25int[] m yArr = new int[5] { 1, 2, 3, 4,
5 };
O bject[] m yO bjArr = new O bject[5]
{ 26, 27, 28, 29, 30 };
Copy 2 elem ent from m yArr to m yO bjArr:
Array.C opy(m yArr,m yO bjArr,2) ;
Trang 26BinarySearch(Array, Object)
Searches an entire one-dimensional sorted Array
interface implemented by each element of the
Array and by the specified object ( not found =-1)
int[] M = new int[5] { 1, 2, 3,
4, 5 };
int found=Array.BinarySearch(M, 8);
Trang 27Method Description
Sort(Array) Sorts the elements in an entire
one-dimensional Array using the IComparable
implementation of each element of the Array
int[] M 1 = new int[]{1,9,2,7,8};
Array.Sort(M 1);
O ut put: 1 2 7 8 9
Trang 28ArrayList Class
using an array whose size is dynamically increased as required
Trang 29Constructors Description
ArrayList () Initializes a new instance of
the ArrayList class that is empty and has the default initial capacity
A rrayList arrList = new
Trang 30Constructors Description
ArrayList(Int32) Initializes a new instance
of the ArrayList class that
is empty and has the specified initial capacity
A rrayList arrList = new
Trang 31(ICollection) Initializes a new instance of the ArrayList class that
contains elements copied from the specified collection and that has the same initial capacity as the number of
elements copied
A rrayList arr1= new A rrayList();
A rrayList arr2 = new A rrayList(arr1);
Trang 32Method Description
Add Adds an object to the end of
the ArrayList
ArrayList arr= new ArrayList();
arr.Add(1);arr.Add( "a" );arr.Add( 9 );
foreach (object item in arr)
Console.W rite(item + “ ”);
//Output : 1 a 9
Trang 33Method Description
AddRange Adds the elements of an
ICollection to the end of the ArrayList
A rrayList arr= new A rrayList();
foreach (int value in arr)
Console.W rite(value+ " ");
//Output : 1 1 4
Trang 34Method Description
Insert Inserts an element into the
ArrayList at the specified index
A rrayList arr= new A rrayList();
foreach (object value in arr)
Console.W rite(value+ " ");
//Output : 1 teo 1 4
Trang 35InsertRange Inserts the elements of a
collection into the ArrayList at the specified index
A rrayList arr= new A rrayList();
arr.AddRange( new int [] { 1, 1, 4 });
A rrayList arrIns= new A rrayList();
arrIns.Add( "teo" );
arrIns.Add( 9 );
foreach ( object value in arr)
Console W rite(value+ " " );
//Output : 1 1 teo 9 4
Trang 36Remove Removes the first occurrence of a
specific object from the ArrayList
A rrayList arr= new A rrayList();
arr.AddRange(new object[]
Trang 37Method Description
RemoveAt Removes the element at the
specified index of the ArrayList
A rrayList arr= new A rrayList();
arr.AddRange(new object[]
Trang 38RemoveRange Removes a range of elements
from the ArrayList
A rrayList arr = new A rrayList();
arr.AddRange(new object[]
{ 1, "teo", 4, "ti" });
arr.Rem oveRange(1, 2);
//1 is Start Index to rem ove
//2 is num ber of elem ent to rem ove
foreach ( object value in arr)
Console W rite(value + " " );
//Output : 1 ti
Trang 39Property Description
Count Gets the number of elements
actually contained in the ArrayList
A rrayList arr= new A rrayList();
arr.AddRange(new object[]
{ 1, "teo", 4, "ti" });
Console.W rite(arr.Count + " ");
//Output : 4
Trang 40Method Description
Clear Removes all elements from the
ArrayList
A rrayList arr= new A rrayList();
arr.AddRange(new object[]
{ 1, "teo", 4, "ti" });
arr.C lear();
Console.W rite(arr.Count + " ");
//Output : 0
Trang 41Contains Determines whether an element
is in the ArrayList
A rrayList arr = new A rrayList ();
"Pheo" , "Thi" , "N o" });
bool bFound = arr.C ontains("N o");
Trang 42IndexOf Searches for the specified Object and
returns the zero-based index of the first occurrence within the entire
ArrayList
A rrayList arr = new A rrayList ();
arr.AddRange( new string [] { "Chi" , "Pheo" ,
"Thi" , "N o" });
int pos1 = arr.IndexO f("Pheo" );
Console W riteLine( "Pos1= " + pos1);
//Output : Pos1=1
int pos2 = arr.IndexO f(“Teo" );
Console W riteLine( "Pos2= " + pos2);
//Output : Pos2=-1
Trang 43Method Description
LastIndexOf Searches for the specified Object
and returns the zero-based index
of the last occurrence within the entire ArrayList
A rrayList arr = new A rrayList ();
arr.AddRange(new string[] { “Teo",
"Pheo", "Thi", “Teo" });
int pos = arr.LastIndexO f(“Teo");
Console.W riteLine("Pos= "+ pos);
//Output : Pos=3
Trang 44Sort Sorts the elements in the entire
Trang 45BinarySearch Searches the entire sorted
ArrayList for an element using the default comparer and returns the zero-based index of the element
A rrayList arr = new A rrayList();
arr.Add(9);arr.Add(7);arr.Add(5);
arr.S ort();//M ust call Sort m ethod
int Found= arr.BinarySearch(9);
Console.W riteLine("Found= "+ Found);
//Output : Found=2
Trang 46Clone Creates a shallow copy of the
ArrayList
A rrayList arr = new A rrayList();
arr.Add(9);arr.Add(7);arr.Add(5);
A rrayList arrN oC lone = arr;
arrN oClone.Rem oveAt(0);
foreach (object val in arr)
Console.W rite(val + " ");
//Output : 7 5
Trang 47What’s happen when We use Clone method???
A rrayList arr = new A rrayList();
Trang 48CopyTo Copies the entire ArrayList to a
compatible one-dimensional Array, starting at the beginning of the target array
A rrayList arr= new ArrayList ();
arr.Add(1);arr.Add( "a" );arr.Add( 9 );
object []M 1= new object [arr.Count];
arr.C opyTo(M 1);
foreach ( object val in M 1)
Console W rite(val + " " );
//Output : 1 a 9
Trang 49A rrayList arr= new ArrayList ();
arr.Add(1);arr.Add( "a" );arr.Add( 9 );
foreach ( object val in M 1)
Console W rite(val + " " );
//Output : 9 a 1
Trang 50Dictionary< TKey , TValue >
Represents a collection of keys and values
Trang 51 Each addition to the
dictionary consists of a value and its associated key.
its key is very fast, close to O(1).
Trang 52 Every key in a Dictionary
<TKey, TValue > must be
unique according to the
dictionary's equality comparer
A key cannot be null , but a
value can be, if the value type
TValue is a reference type
Trang 53 The capacity is automatically
increased as required by
reallocating the internal array
Use KeyValuePair <TKey, TValue >
structure representing a value and its key.
Trang 54Dictionary <TKey, TValue >()
Description:
Initializes a new instance of the
Dictionary <TKey, TValue > class
that is empty, has the default
initial capacity, and uses the
default equality comparer for the key type
Trang 55// Create a new dictionary of
ArrayList, with string keys.
Dictionary < string , ArrayList >
Dictionary < string , ArrayList >();
Trang 56// Or
Dictionary<string, ArrayList > myDIC = new
Dictionary<string, ArrayList >
(StringCom parer CurrentCultureIgnoreCase
);
Trang 57Add ( TKey key, TValue value )
Trang 59A rrayList aItem = m yD IC["H om e"];
foreach ( K eyValuePair< string,
A rrayList> item in m yD IC){
string strK ey = item Key;
A rrayList arrValue = item Value;
}
KeyValuePair <TKey, TValue>
Defines a key/value pair that can be set or
retrieved
Trang 61public bool ContainsKey (TKey key)
Description:
Determines whether the
Dictionary <TKey,TValue>
contains the specified key
if (m yD IC.C ontainsK ey("H om e"))
{
M essageBox.Show (“Có hom e");
}
Trang 62public bool ContainsValue
(TValue value )
Description:
Determines whether the
Dictionary <TKey, TValue>
contains a specific value
if (m yD IC.C ontainsValue(arr))
{M essageBox Show ( "Có Arr này rỗồ i" );
}
Trang 63public bool TryGetValue
(TKey key, out TValue value )
Description:
Gets the value associated with the specified
key
A rrayList arr = null ;
if (m yD IC.TryG etValue( "H om e" , out arr))
{ //Process arr here
}
else { //Could not G et value
}
Trang 65Count
Description:
Gets the number of key/value
pairs contained in the
Dictionary <TKey, TValue >
Trang 66ArgumentNullException=>key is null
A rrayList aItem = m yD IC["H om e"];
m yD IC["H om e"]= arr (A rraylist);
Trang 67Description:
Gets a collection containing the keys in the
Dictionary <TKey, TValue > Example:
D ictionary < string , A rrayList >
m yD IC.K eys;
foreach (string s in keyColl)
{//Process Key here
}
Trang 68Description:
Gets a collection containing the values in the
Dictionary <TKey, TValue > Example:
D ictionary< string, A rrayList>
m yD IC.Values;
foreach(A rrayList arr in valColl)
{//Process value here
}
Trang 69END