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

Làm thế nào để tạo một bản sao ngắn của ArrayList trong C #?

Để tạo một bản sao ngắn của ArrayList trong C #, mã như sau -

Ví dụ

 using System; using System.Collections; public class Demo {public static void Main () {ArrayList list =new ArrayList (); list.Add ("Một"); list.Add ("Hai"); list.Add ("Ba"); list.Add ("Bốn"); list.Add ("Năm"); list.Add ("Sáu"); list.Add ("Bảy"); list.Add ("Tám"); Console.WriteLine ("Các phần tử ArrayList ..."); foreach (chuỗi str trong danh sách) {Console.WriteLine (str); } Console.WriteLine ("ArrayList is only read-only? =" + List.IsReadOnly); Console.WriteLine ("Phần tử Six có trong ArrayList không? =" + List.Contains ("Six")); list.Insert (4, "Twelve"); Console.WriteLine ("\ nArrayList phần tử ... ĐÃ CẬP NHẬT"); foreach (chuỗi str trong danh sách) {Console.WriteLine (str); } ArrayList list2 =new ArrayList (); list2 =(ArrayList) list.Clone (); Console.WriteLine ("\ nDanh sách ArrayLloned ..."); foreach (string str trong list2) {Console.WriteLine (str); }}} 

Đầu ra

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

Các phần tử
 ArrayList ... OneTwoThreeFourFiveSixSevenEightArrayList là chỉ đọc? =False Có phần tử Six trong ArrayList không? =Các phần tử TrueArrayList ... UPDATEDOneTwoThreeFourTwelveFiveSixSevenEightCloned ArrayList ... OneTwoThreeFourTwelveFiveSixSevenEight 

Ví dụ

Bây giờ chúng ta hãy xem một ví dụ khác -

 using System; using System.Collections; public class Demo {public static void Main (String [] args) {ArrayList list1 =new ArrayList (); list1.Add ("A"); list1.Add ("B"); list1.Add ("C"); list1.Add ("D"); list1.Add ("E"); list1.Add ("F"); list1.Add ("G"); list1.Add ("H"); list1.Add ("Tôi"); Console.WriteLine ("Các phần tử trong ArrayList1 ..."); foreach (chuỗi res trong list1) {Console.WriteLine (res); } ArrayList list2 =new ArrayList (); list2.Add ("A"); list2.Add ("B"); list2.Add ("C"); list2.Add ("D"); list2.Add ("E"); list2.Add ("F"); list2.Add ("G"); list2.Add ("H"); list2.Add ("Tôi"); list2.Add ("G"); list2.Add ("Tôi"); Console.WriteLine ("Các phần tử trong ArrayList2 ..."); foreach (chuỗi res trong list2) {Console.WriteLine (res); } Console.WriteLine ("Số phần tử trong ArrayList2 =" + list2.Count); list2.Remove ("G"); Console.WriteLine ("Các phần tử trong ArrayList2 ... (CẬP NHẬT)"); foreach (chuỗi res trong list2) {Console.WriteLine (res); } Console.WriteLine ("Số phần tử trong ArrayList2 (Đã cập nhật) =" + list2.Count); ArrayList list3 =new ArrayList (); list3 =(ArrayList) list2.Clone (); Console.WriteLine ("\ nDanh sách ArrayList từ ArrayList2 ..."); foreach (string str trong list3) {Console.WriteLine (str); }}} 

Đầu ra

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

 Phần tử trong ArrayList1 ... ABCDEFGHIE Thực hiện trong ArrayList2 ... ABCDEFGHIGTìm số lượng phần tử trong ArrayList2 =11 Phần tử trong ArrayList2 ... (CẬP NHẬT) ABCDEFHIGIC Số lượng phần tử trong ArrayList2 (Đã cập nhật) =10 Danh sách mảng được mở từ ArrayList2 ... ABCDEFHIGI