You are on page 1of 11

1.

ArrayList
Để tạo một đối tượng của ArrayList ta sử dụng từ khóa new.
ArrayList arlist = new ArrayList();
// hoặc
var arlist = new ArrayList();
Chúng ta có thể sử dụng phương thức Add() hoặc cú pháp trình khởi tạo đối
tượng để thêm một phần tử vào ArrayList.Trong một ArrayList có thể chứa nhiều
giá trị null trùng lặp nhau.
// thêm phần tử vào ArrayList sử dụng phương thức Add()
var arlist1 = new ArrayList();
arlist1.Add(1);
arlist1.Add("Freetuts.net");
arlist1.Add(" ");
arlist1.Add(true);
arlist1.Add(4.5);
arlist1.Add(null);

// thêm phần tử vào ArrayList bằng cách khởi tạo cho các đối tượng
var arlist2 = new ArrayList()
{
2, "Freetuts.net", true, 4.5, null
};
//khai báo một ArrayList
var arlist2 = new ArrayList()
{
1, "Freetuts.net", " ", true, 4.5, null
};
//khai báo một ArrayList
int[] arr = { 100, 200, 300, 400 };

//Thêm một ArrayList vào ArrayList


arlist1.AddRange(arlist2);
//Thêm một Array vào ArrayList
arlist1.AddRange(arr);
Chúng ta có thể truy cập vào ArrayList bằng cách sử dụng trình chỉ mục giống
như cách truy cập vào Array. Chỉ mục bắt đầu từ 0 và tăng lên 1 cho mỗi phần tử
kế tiếp. Cần phải truyền kiểu dữ liệu rõ ràng hoặc sử dụng biến var.
var arlist = new ArrayList()
{
1,
"Freetuts.net",
300,
4.5f
};

//truyền kiểu dữ liệu tương ứng như int, string


int firstElement = (int) arlist[0]; //returns 1
string secondElement = (string) arlist[1]; //returns "Bill"

//truyền kiểu dữ liệu sử dụng biến var


var firstElement = arlist[0]; //returns 1
var secondElement = arlist[1]; //returns "Bill"
Để chèn một phần tử vào trong ArrayList tại một chỉ mục được chỉ định ta sử
dụng phương thức Insert().
ArrayList arlist = new ArrayList()
{
1,
"Freetuts.net",
300,
4.5f
};
arlist.Insert(1, "Second Item");
Ngoài ra ta có thể chèn một ArrayList vào vào ArrayList bằng phương thức
InsertRange().
ArrayList arlist1 = new ArrayList()
{
100, 200, 600
};

ArrayList arlist2 = new ArrayList()


{
300, 400, 500
};
arlist1.InsertRange(2, arlist2);
Để xóa phần tử khỏi ArrayList ta có thể sử dụng các phương thức Remove(),
RemoveAt() và RemoveRange().
ArrayList arList = new ArrayList()
{
1,
null,
"Freetuts.net",
300,
" ",
4.5f,
300,
};

arList.Remove(null);
arList.RemoveAt(4);
arList.RemoveRange(0, 2);
Sử dụng phương thức Contains() để kiểm tra một phần tử được chỉ định có
nằm trong ArrayList hay không. Nó trả về true nếu tồn tại và trả về false nếu không
tồn tại.
ArrayList arList = new ArrayList()
{
1,
"Freetuts.net",
300,
4.5f,
300
};
Console.WriteLine(arList.Contains(300)); // true
Console.WriteLine(arList.Contains("Freetuts.net")); // true
Console.WriteLine(arList.Contains(10)); // false
Console.WriteLine(arList.Contains("Freetuts")); // false

2. SortedList

Ví dụ dưới đây minh họa cho cách tạo một SortedList và thêm các cặp
key.value vào trong SortedList.
numberNames.Add(3, "Three");
numberNames.Add(1, "One");
numberNames.Add(2, "Two");
numberNames.Add(4, null);
numberNames.Add(10, "Ten");
numberNames.Add(5, "Five");

SortedList<string,string> cities = new SortedList<string,string>()


{
{"London", "UK"},
{"New York", "USA"},
{ "Mumbai", "India"},
{"Johannesburg", "South Africa"}
};

Ta có thể truy cập vào SortedList bằng cách sử dụng key để lấy hoặc đặt lại
value trong SortedList.
SortedList<int,string> numberNames = new SortedList<int,string>()
{
{3, "Three"},
{1, "One"},
{2, "Two"}
};

Console.WriteLine(numberNames[1]); //kết quả: One


Console.WriteLine(numberNames[2]); //kết quả: Two
Console.WriteLine(numberNames[3]); //kết quả: Three

Ngoài ra có thể sử dụng phương thức ContainsKey và TryGetValue() để truy


cập vào SortedList.
SortedList<int,string> numberNames = new SortedList<int,string>()
{
{3, "Three"},
{1, "One"},
{2, "Two"}
};
//nếu key tồn tại
if(!numberNames.ContainsKey(4))
{
numberNames[4] = "Four";
}

string result;

if(numberNames.TryGetValue(4, out result))


Console.WriteLine("Key: {0}, Value: {1}", 4, result);
Để xóa các cặp key/value khỏi SortedList ta có thể sử dụng phương thức
Remove() và RemoveAt().
SortedList<int,string> numberNames = new SortedList<int,string>()
{
{3, "Three"},
{1, "One"},
{2, "Two"},
{5, "Five"},
{4, "Four"},
};

numberNames.Remove(1);// xóa phần tử có key = 1


numberNames.RemoveAt(0);//xóa phần tử có key == 0

3. Stack
Ví dụ dưới đây minh họa cho việc tạo Stack và thêm các item vào Stack bằng
phương thức Push().
using System;
using System.Collections.Generic;
class Program
{
public static void Main(string[] args)
{
//khai báo một stack lưu trữ các item kiểu int
Stack<int> numbers = new Stack<int>();
//sử dụng phương thức Push() để lưu trữ các item
numbers.Push(1);
numbers.Push(2);
numbers.Push(3);
numbers.Push(4);
//sử dụng foreach để in phần tử trong Stack
Console.WriteLine("\nCác phần tử trong Stack là:");
foreach (var item in numbers)
Console.Write(item + ",");

Console.WriteLine("\n\n---------------------------------");
Console.WriteLine("Chương trình này được đăng tại Freetuts.net");
}
}

Ngoài ra ta cũng có thể tạo Stack bằng mảng.


using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
int[] arr = new int[] { 1, 2, 3, 4, 5, 6 };
Stack<int> myStack = new Stack<int>(arr);
Console.WriteLine("\nCác phần tử trong Stack:");
foreach (var itm in myStack)
Console.Write(itm + ",");

Console.WriteLine("\n\n---------------------------------");
Console.WriteLine("Chương trình này được đăng tại Freetuts.net");
}
}

Phương thức Pop() trả về item cuối cùng trong Stack đồng thời loại bỏ nó khỏi
Stack.Nếu Stack trống thì nó trả về InvalidOperationException, vì vậy hãy luôn
kiểm tra số phần tử trong ngăn xếp trước khi gọi phương thức Pop().

using System;
using System.Collections;
public class Program
{
public static void Main()
{
Stack myStack = new Stack();
myStack.Push(1);
myStack.Push(2);
myStack.Push(3);
myStack.Push(4);

Console.WriteLine("\nSố phần tử trong Stack trước khi xóa: {0}",


myStack.Count);
//xóa một phần tử trên cùng trong Stack
myStack.Pop();

Console.WriteLine();
Console.WriteLine("Số phần tử trong Stack sau khi xóa: {0}",
myStack.Count);

Console.WriteLine("\n\n---------------------------------");
Console.WriteLine("Chương trình này được đăng tại Freetuts.net");
}
}

Phương thức Contains() kiểm tra một item có tồn tại trong Stack hay không.
Nếu tồn tại nó thì trả về true, nếu không thì trả về false.
using System;
using System.Collections;
public class Program
{
public static void Main()
{
Stack myStack = new Stack();
myStack.Push(1);
myStack.Push(2);
myStack.Push(3);
myStack.Push(4);

Console.WriteLine("\nSố phần tử trong Stack trước khi dùng Peek():


{0}", myStack.Count);
//xóa một phần tử trên cùng trong Stack
Console.WriteLine("Phần tử trên cùng trong Stack:
{0}",myStack.Peek());

Console.WriteLine();
Console.WriteLine("Số phần tử trong Stack sau khi dùng Peek(): {0}",
myStack.Count);

Console.WriteLine("\n\n---------------------------------");
Console.WriteLine("Chương trình này được đăng tại Freetuts.net");
}
}

Phương thức Contains() kiểm tra một item có tồn tại trong Stack hay không.
Nếu tồn tại nó thì trả về true, nếu không thì trả về false.
using System;
using System.Collections.Generic;

public class Program


{
public static void Main()
{
Stack<int> myStack = new Stack<int>();
myStack.Push(1);
myStack.Push(2);
myStack.Push(3);
myStack.Push(4);

Console.WriteLine(myStack.Contains(2));// ->> true


Console.WriteLine(myStack.Contains(10));// -> false

Console.WriteLine("\n\n---------------------------------");
Console.WriteLine("Chương trình này được đăng tại Freetuts.net");
}
}

4. Queue
Chúng ta có thể tạo đối tượng của Queue bằng cách chỉ định một tham số có
kiểu dữ liệu mà nó có thể lưu trữ. Queue cho phép lưu giá trị null (đối với các loại
tham chiếu) và các giá trị trùng lặp.
Queue<int> callerIds = new Queue<int>();

Ví dụ dưới đây minh họa cho việc tạo Queue và thêm các item vào Queue
bằng phương thức Enqueue().
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
//khai báo một queue
Queue<int> callerIds = new Queue<int>();
//sử dụng phương thức Enqueue() để thêm item vào Queue
callerIds.Enqueue(1);
callerIds.Enqueue(2);
callerIds.Enqueue(3);
callerIds.Enqueue(4);
Console.WriteLine("\nCác phần tử trong Queue: ");
foreach (var id in callerIds)
Console.WriteLine(id);

Console.WriteLine("\n\n---------------------------------");
Console.WriteLine("Chương trình này được đăng tại Freetuts.net");
}
}

Để lấy phần tử của Queue ta có hai phương thức đó là Dequeue() và Peek.


Phương thức Dequeue() sẽ lấy phần tử đầu tiên trong Queue đồng thời loại bỏ nó
khỏi Queue. Khi Queue rỗng nếu chúng ta gọi hai phương thức trên thì nó sẽ trả về
InvalidOperationException. Vì vậy hãy kiểm tra Queue trước khi sử dụng hai
phương thức này nhé.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
Queue<string> strQ = new Queue<string>();
strQ.Enqueue("H");
strQ.Enqueue("e");
strQ.Enqueue("l");
strQ.Enqueue("l");
strQ.Enqueue("o");

Console.WriteLine("\nTổng số phần tử trong Queue trước khi sử


dụng Dequeue(): {0}", strQ.Count);
//sử dụng phương thức Dequeue() để lấy và xóa phần tử đầu tiên
Console.WriteLine("Phần tử đã xóa: " + strQ.Dequeue());

Console.WriteLine("Tổng số phần tử trong Queue sau khi sử dụng


Dequeue(): {0}", strQ.Count);

Console.WriteLine("\n\n---------------------------------");
Console.WriteLine("Chương trình này được đăng tại Freetuts.net");
}
}

Còn phương thức Peek() chỉ lấy phần tử đầu tiên trong Queue mà không loại
bỏ nó.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
Queue<string> strQ = new Queue<string>();
strQ.Enqueue("H");
strQ.Enqueue("e");
strQ.Enqueue("l");
strQ.Enqueue("l");
strQ.Enqueue("o");

Console.WriteLine("\nTổng số phần tử trong Queue trước khi sử


dụng Peek(): {0}", strQ.Count);
//sử dụng phương thức peek() để lấy và xóa phần tử đầu tiên
Console.WriteLine("Phần tử đã lấy ra: " + strQ.Peek());

Console.WriteLine("Tổng số phần tử trong Queue sau khi sử dụng


Peek(): {0}", strQ.Count);

Console.WriteLine("\n\n---------------------------------");
Console.WriteLine("Chương trình này được đăng tại Freetuts.net");
}
}

Phương thức Contains() kiểm tra một item có tồn tại trong Queue hay không.
Nếu tồn tại nó thì trả về true, nếu không thì trả về false.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
Queue<int> callerIds = new Queue<int>();
callerIds.Enqueue(1);
callerIds.Enqueue(2);
callerIds.Enqueue(3);
callerIds.Enqueue(4);
Console.WriteLine(callerIds.Contains(2)); //true
Console.WriteLine(callerIds.Contains(10)); //false

Console.WriteLine("\n\
n---------------------------------");
Console.WriteLine("Chương trình này được đăng tại Freetuts.net");
}
}

6. Dictionary
Chúng ta có thể tạo một Dictionary bằng cách truyền vào key và value cần lưu
trữ. Ví dụ dưới đây là cách tạo một Dictionary và cách thêm các cặp key/value cho
nó.
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
//khai báo và khởi tạo một Dictionary
var cities = new Dictionary<string, string>(){
{"UK", "London, Manchester, Birmingham"},
{"USA", "Chicago, New York, Washington"},
{"India", "Mumbai, New Delhi, Pune"}
};

Console.WriteLine("---Các phần tử trong Dictionary---");


//sử dụng phương thức ElementAt() để truy cập vào Dictionary
for (int i = 0; i < cities.Count; i++)
{
Console.WriteLine("Key: {0}, Value: {1}",
cities.ElementAt(i).Key,
cities.ElementAt(i).Value);
}

Console.WriteLine("----------------------------------------");
Console.WriteLine("Chương trình này được đăng tại Freetuts.net");
}
}

Dictionary có thể được truy cập bằng cách sử dụng indexer (trình chỉ mục) để
chỉ đinh một key liên kết với value.Ta có thể sử dụng phương thức ElementAt() để
lấy KeyValuePair từ chỉ mục được chỉ định.
using System;
using System.Linq;
using System.Collections.Generic;

public class Program


{
public static void Main()
{
//khai báo và khởi tạo một Dictionary
var cities = new Dictionary<string, string>(){
{"UK", "London, Manchester, Birmingham"},
{"USA", "Chicago, New York, Washington"},
{"India", "Mumbai, New Delhi, Pune"}
};
Console.WriteLine("\n-----------------Dictionary ban
đầu----------------------");
foreach(var kvp in cities)
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);

cities["UK"] = "Liverpool, Bristol";


cities["USA"] = "Los Angeles, Boston";

if(cities.ContainsKey("France")){
cities["France"] = "Paris";
}
Console.WriteLine("\n-----------------Dictionary sau khi cập
nhật----------------------");
foreach(var kvp in cities)
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);

Console.WriteLine("----------------------------------------");
Console.WriteLine("Chương trình này được đăng tại Freetuts.net");
}
}

Cập nhật value của một key bằng cách chỉ định một key trong indexer (trình
chỉ mục). Trước khi cập nhật ta nên kiểm tra key có tồn tại hay không bằng phương
thức ContainsKey().

Để xóa các cặp key/value trong Dictionary ta có hai phương thức. Phương
thức Remove() để xóa một cặp key/value và phương thức Clear() để xóa tất cả các
cặp key/value.
using System;
using System.Collections.Generic;

public class Program


{
public static void Main()
{
var cities = new Dictionary<string, string>(){
{"UK", "London, Manchester, Birmingham"},
{"USA", "Chicago, New York, Washington"},
{"India", "Mumbai, New Delhi, Pune"}
};
foreach(var kvp in cities)
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
//đếm số phần tử lần 1
Console.WriteLine("\nTổng các phần tử: {0}", cities.Count);

//sử dụng phương thức Remove() để xóa một cặp key/value


cities.Remove("UK");
//sử dụng phương thức ContainsKey() để kiểm tra xem key "France"
có tồn tại hay không
//nếu có thì xóa, nếu không thì không xóa
if(cities.ContainsKey("France")){
cities.Remove("France");
}
//đếm số phần tử lần 2
Console.WriteLine("Tổng các phần tử sau khi xóa một phần tử: {0}",
cities.Count);

//sử dụng phương thức Clear() để xóa toàn bộ các phần tử


cities.Clear(); //deletes all elements
//đếm lần 3
Console.WriteLine("Tổng các phần tử sau khi xóa hết: {0}",
cities.Count);

Console.WriteLine("----------------------------------------");
Console.WriteLine("Chương trình này được đăng tại Freetuts.net");
}
}

7. HashSet
HashSet<int> hashset1 = new HashSet<int>() {5,2,3,4};
Console.WriteLine($"Phần tử trong hashset1 {hashset1.Count}");
foreach (var v in hashset1)
{
Console.Write(v + " ");
}
Console.WriteLine();

HashSet<int> hashset2 = new HashSet<int>();


hashset2.Add(3);
hashset2.Add(4);
if (hashset1.IsSupersetOf(hashset2))
Console.WriteLine($"hashset1 là tập chứa hashset2");

/*
Phần tử trong hashset1 4
5 2 3 4
hashset1 là tập chứa hashset2
*/

You might also like