Để lấy tập hợp các giá trị (values) từ ListDictionary dưới dạng ICollection, bạn sử dụng thuộc tính Values. Thuộc tính này trả về một collection chỉ đọc chứa tất cả các giá trị trong từ điển.
Ví dụ 1: Lấy values và duyệt qua ICollection
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
ListDictionary listDict = new ListDictionary();
listDict.Add("1", "Laptop");
listDict.Add("2", "Tablet");
listDict.Add("3", "Desktop");
listDict.Add("4", "Speaker");
listDict.Add("5", "Earphone");
listDict.Add("6", "Headphone");
// Lấy ICollection chứa các values
ICollection col = listDict.Values;
Console.WriteLine("Các giá trị trong ListDictionary:");
foreach (String s in col)
{
Console.WriteLine(s);
}
}
}
Kết quả
Laptop Tablet Desktop Speaker Earphone Headphone
Ví dụ 2: Ví dụ khác với tên người
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
ListDictionary listDict = new ListDictionary();
listDict.Add("A", "Tom");
listDict.Add("B", "John");
listDict.Add("C", "Kevin");
listDict.Add("D", "Tim");
ICollection col = listDict.Values;
Console.WriteLine("Các giá trị trong ListDictionary:");
foreach (String s in col)
{
Console.WriteLine(s);
}
}
}
Kết quả
Tom John Kevin Tim
Các cách khác để làm việc với Values
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Linq;
public class Demo
{
public static void Main()
{
ListDictionary dict = new ListDictionary();
dict.Add("A", "Apple");
dict.Add("B", "Banana");
dict.Add("C", "Cherry");
// 1. Duyệt trực tiếp (khuyến nghị)
foreach (var value in dict.Values)
{
Console.WriteLine(value);
}
// 2. Chuyển thành mảng
string[] valuesArray = new string[dict.Values.Count];
dict.Values.CopyTo(valuesArray, 0);
// 3. Chuyển thành List (cần using System.Linq)
var valuesList = dict.Values.Cast<string>().ToList();
// 4. Kiểm tra giá trị tồn tại
bool hasBanana = dict.Values.Cast<string>().Contains("Banana");
Console.WriteLine("Có 'Banana'? " + hasBanana);
// 5. Đếm số lượng
Console.WriteLine("Số lượng values: " + dict.Values.Count);
}
}
Lưu ý quan trọng
ListDictionary.Valuestrả vềICollection- chỉ đọc, không thể thêm/xóa/sửa trực tiếp- Thứ tự values tương ứng với thứ tự keys (theo insertion order)
- Có thể chứa giá trị trùng lặp (khác với Keys)
- Value có thể là
null - Để sửa giá trị, phải gán qua key:
dict["A"] = "New Value"
So sánh với Dictionary<TKey, TValue>
// Dictionary<TKey, TValue> (hiện đại, khuyến nghị)
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("A", "Apple");
// Lấy values
var values = dict.Values; // Trả về ValueCollection (implements ICollection<TValue>)
// Duyệt
foreach (var v in values) { ... }
// Chuyển List
var list = values.ToList(); // Cần using System.Linq