Computer >> Máy Tính >  >> Lập trình >> C#

Xóa một loạt các phần tử khỏi Danh sách trong C #

Để xóa một loạt các phần tử khỏi Danh sách, mã như sau -

Ví dụ

 using System; using System.Collections.Generic; public class Demo {public static void Main (String [] args) {List  list1 =new List  (); list1.Add ("Một"); list1.Add ("Hai"); list1.Add ("Ba"); list1.Add ("Bốn"); list1.Add ("Năm"); Console.WriteLine ("Các phần tử trong List1 ..."); foreach (chuỗi res trong list1) {Console.WriteLine (res); } List  list2 =new List  (); list2.Add ("Ấn Độ"); list2.Add ("US"); list2.Add ("Anh"); list2.Add ("Canada"); list2.Add ("Ba Lan"); list2.Add ("Hà Lan"); Console.WriteLine ("Các phần tử trong List2 ..."); foreach (chuỗi res trong list2) {Console.WriteLine (res); } Console.WriteLine ("\ nCó phải List2 bằng List1 không? =" + List2.Equals (list1)); Console.WriteLine ("\ nTính số phần tử trong list2 =" + list2.Count); list2.RemoveRange (1,3); Console.WriteLine ("\ nTính số phần tử trong list2 (đã cập nhật) =" + list2.Count); Console.WriteLine ("Các phần tử trong List2 ... ĐÃ CẬP NHẬT"); foreach (chuỗi res trong list2) {Console.WriteLine (res); }}} 

Đầu ra

Điều này sẽ tạo ra kết quả sau -

 Các phần tử trong List1 ... OneTwoThreeFourFiveElements trong List2 ... IndiaUSUKCanadaPolandNetherlandsIs List2 bằng List1? =Sai Số lượng phần tử trong list2 =6 Số lượng phần tử trong list2 (đã cập nhật) =3 Thực hiện trong List2 ... UPDATEDIndiaPolandNetherlands 

Ví dụ

Hãy để chúng tôi xem một ví dụ khác -

 using System; using System.Collections.Generic; public class Demo {public static void Main (String [] args) {List  list =new List  (); list.Add ("Ấn Độ"); list.Add ("US"); list.Add ("Vương quốc Anh"); list.Add ("Canada"); list.Add ("Ba Lan"); list.Add ("Hà Lan"); list.Add ("Bhutan"); list.Add ("Singapore"); Console.WriteLine ("Các phần tử trong Danh sách ..."); foreach (chuỗi res trong danh sách) {Console.WriteLine (res); } Console.WriteLine ("\ nTính số phần tử trong list =" + list.Count); list.RemoveRange (1,3); Console.WriteLine ("\ nTính số phần tử trong list2 (đã cập nhật) =" + list.Count); Console.WriteLine ("Các phần tử trong Danh sách ... ĐÃ CẬP NHẬT"); foreach (chuỗi res trong danh sách) {Console.WriteLine (res); } list.RemoveRange (2,3); Console.WriteLine ("\ nTính số phần tử trong list2 (đã cập nhật) =" + list.Count); Console.WriteLine ("Các phần tử trong Danh sách ... ĐÃ CẬP NHẬT"); foreach (chuỗi res trong danh sách) {Console.WriteLine (res); }}} 

Đầu ra

Điều này sẽ tạo ra kết quả sau -

 Các phần tử trong danh sách ... IndiaUSUKCanadaPolandNetherlandsBhutanSingaporeTổng số phần tử trong danh sách =8Số phần tử trong danh sách2 (cập nhật) =5Các phần tử trong danh sách ... CẬP NHẬT