Thứ Hai, 3 tháng 5, 2010

// // 1 comment

Dictionary Collection C#

Dictionary là dữ liệu kiểu collection có chứa cặp Key/Value, giống như HashTable, chỉ khác kiểu khai báo cho Key và Value. Dữ liệu mà Dictionary lưu trữ là bất kỳ đối tượng nào. Key hoặc Value có thể chứa các kiểu dữ liệu như int,string,.. , mảng array, kiểu liệt kê, hoặc thậm chí là kiểu struct. Cú pháp khai báo:
Dictionary<int, string> newDict = new Dictionary<int, string>();

Để thêm một cặp giá trị vào Dictionay ta sử dụng phương thức Add();
newDict.Add(1, "Chuỗi thứ nhất"); // Chuỗi thứ tư có khóa key là 1
newDict.Add(2, "Chuỗi thứ hai");
newDict.Add(3, "Chuỗi thứ ba");
newDict.Add(100, "Chuỗi thứ tư"); // Chuỗi thứ tư có khóa key là 100


Để lấy dữ liệu ra cho việc hiển thị, cú pháp tương tự như khi làm việc với mảng, thay vào đó là khóa key của Dictionary:
Console.WriteLine(newDict[2]);


Một ví dụ khác:

Dictionary<Color, string> colorStrings = new Dictionary<Color, string>();
colorStrings.Add(Color.Black, Color.Black.ToString());
colorStrings.Add(Color.Blue, Color.Blue.ToString());
colorStrings.Add(Color.Red, Color.Red.ToString());
foreach (KeyValuePair<Color, string> color in colorStrings)
{
  Console.WriteLine(color.Key.GetBrightness().ToString());
}
//Outputs: 0 0.5 0.5

* Một số thao tác làm việc với Dictionary:
- Sao chép Một từ điển Dictionay sẵn có sang một Dictionary mới (là copy)
Dictionary<string, int> copy = new Dictionary<string, int>(newDict);

Ví dụ:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        //
        // Create and initialize Dictionary.
        //
        Dictionary dictionary = new Dictionary();
        dictionary.Add("cat", 1);
        dictionary.Add("dog", 3);
        dictionary.Add("iguana", 5);

        //
        // Copy the Dictionary to a second object.
        //
        Dictionary copy = new Dictionary(dictionary);

        //
        // Change the first Dictionary. It won't change the copy.
        //
        dictionary.Add("fish", 4);

        //
        // Display the first Dictionary.
        //
        Console.WriteLine("--- Dictionary 1 ---");
        foreach (var pair in dictionary)
        {
            Console.WriteLine(pair);
        }
        //
        // Display the second Dictionary.
        //
        Console.WriteLine("--- Dictionary 2 ---");
        foreach (var pair in copy)
        {
            Console.WriteLine(pair);
        }
    }
}
* Kết quả
--- Dictionary 1 ---
[cat, 1]
[dog, 3]
[iguana, 5]
[fish, 4]
--- Dictionary 2 ---
[cat, 1]
[dog, 3]
[iguana, 5]
  
* Việc sửa chữa, thêm bớt Dictionary 1 không làm ảnh hưởng đến Dictionary 2 sau khi đã sao chép.
- Thế còn trường hợp mà ta muốn sao chép một Dict 1  đã sẵn chứa dữ liệu sang một Dict 2 khác cũng đã tồn tại dữ liệu rồi thì sao.
Nếu làm giống như ví dụ trên thì cặp dữ liệu sẵn có trong Dict 2 sẽ bị xóa hết trước khi được copy
Để làm được việc này thì bạn phải thông qua kiểu struct KeyValuePair

Ví dụ : Giả sử bạn muốn sao chép toàn bộ dữ liệu đang sẵn chứa trong Dict2 sang Dict1 (Dict cũng đang chứa dữ liệu của nó, lưu ý là Dict1 và Dict2 cùng có cặp KEY/VALUE là giống nhau ở đây KEY lưu dữ liệu kiểu string, VALUE lưu kiểu HocPhanDto).
foreach (KeyValuePair<string, HocPhanDto> item in Dict2)
{
// Kiểm tra xem Dict1 có sẵn chứa cặp dữ liệu có trong Dict2 hay không;
// Việc làm này tránh xung đột dữ liệu,
// do Dictionary chỉ được phép tồn tại duy nhất một cặp Key/Value;

if (ListHocPhan.ContainsKey(item.Key)) continue;// Bỏ qua công việc phía sau lệnh này và tiếp tục vòng lặp foreach; // else
// Thực hiện thêm dữ liệu vào Dict1;

Dict1.Add(item.Key, item.Value); }
...

1 comments:

Becon nói...

Thanks a lot, good luck for me!