การใช้ ArrayList ในภาษา C# มีรูปแบบการเขียนโค้ดดังนี้
ส่วนหัวของโปรแกรมที่จำเป็น :
using System.Collections;ตัวอย่างการใช้งาน :
ArrayList myAL = new ArrayList(); // Creates and initializes a new ArrayList. myAL.Add("PEEZ"); myAL.Add("Glorious"); myAL.Add("Intel"); myAL.Add("blogspot"); // myAL is {"PEEZ","Glorious","Intel","blogspot"} string strSimple = "1234"; myAL.Add(strSimple); // "1234" is added // myAL is {"PEEZ","Glorious","Intel","blogspot","1234"} myAL.Remove("blogspot"); // "blogspot" is removed // myAL is {"PEEZ","Glorious","Intel","1234"} myAL.RemoveAt(3); // myAL[3] (that means "1234") is removed // myAL is {"PEEZ","Glorious","Intel"} myAL.Sort(); // sorted all items in myAL // myAL is {"Glorious","Intel","PEEZ"} myAL.Reverse(); // reverse all items in myAL // myAL is {"PEEZ","Intel","Glorious"} Console.WriteLine("count : " + myAL.Count); foreach(string item in myAL) { Console.WriteLine(item); } myAL.Clear(); // Removes all elements /* output is * * count : 3 * PEEZ * Intel * Glorious * */นอกจากตัวแปรประเภท string แล้ว ArrayList สามารถใช้กับตัวแปรประเภทอื่นๆ และ Array ได้
ตัวอย่างการเขียนโปรแกรม :
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; class Program { static int sum_array(int[] num) { int sum = 0; foreach(int n in num) sum += n; return sum; } static void Main() { ArrayList myAL2 = new ArrayList(); int[] num1 = { 1, 2, 3 }; int[] num2 = { 100, 200, 300 }; myAL2.Add(num1); myAL2.Add(num2); foreach (int [] item in myAL2) Console.WriteLine(sum_array(item)); } } /* output is * * 6 * 600 * */see more properties and methods:
http://msdn.microsoft.com/en-us/library/system.collections.arraylist.aspx
see more examples:
http://www.dotnetperls.com/arraylist
No comments:
Post a Comment