Giới thiệu
Để xóa lần xuất hiện đầu tiên của một giá trị cụ thể trong LinkedList<T>, bạn sử dụng phương thức Remove(T). Phương thức này trả về true nếu tìm thấy và xóa thành công, ngược lại trả về false.
Ví dụ 1: Xóa giá trị "A" xuất hiện nhiều lần
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
LinkedList<string> list = new LinkedList<string>();
list.AddLast("A");
list.AddLast("B");
list.AddLast("C");
list.AddLast("A");
list.AddLast("E");
list.AddLast("F");
list.AddLast("A");
list.AddLast("H");
list.AddLast("A");
list.AddLast("j");
Console.WriteLine("Số lượng nút = " + list.Count);
Console.WriteLine("Các phần tử trong LinkedList...");
foreach (string res in list)
Console.WriteLine(res);
list.Remove("A");
Console.WriteLine("Số lượng nút = " + list.Count);
Console.WriteLine("Các phần tử trong LinkedList... (sau khi xóa)");
foreach (string res in list)
Console.WriteLine(res);
}
}
Kết quả
Số lượng nút = 10 Các phần tử trong LinkedList... A B C A E F A H A j Số lượng nút = 9 Các phần tử trong LinkedList... (sau khi xóa) B C A E F A H A j
Ví dụ 2: Xóa giá trị "Three" xuất hiện liên tiếp
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
LinkedList<string> list = new LinkedList<string>();
list.AddLast("One");
list.AddLast("Two");
list.AddLast("Three");
list.AddLast("Three");
list.AddLast("Three");
list.AddLast("Four");
Console.WriteLine("Số lượng nút = " + list.Count);
Console.WriteLine("Các phần tử trong LinkedList...");
foreach (string res in list)
Console.WriteLine(res);
list.Remove("Three");
Console.WriteLine("Số lượng nút = " + list.Count);
Console.WriteLine("Các phần tử trong LinkedList... (sau khi xóa)");
foreach (string res in list)
Console.WriteLine(res);
}
}
Kết quả
Số lượng nút = 6 Các phần tử trong LinkedList... One Two Three Three Three Four Số lượng nút = 5 Các phần tử trong LinkedList... (sau khi xóa) One Two Three Three Four
Lưu ý: Chỉ có lần xuất hiện đầu tiên (tính từ đầu danh sách) bị xóa. Các lần xuất hiện sau vẫn giữ nguyên.