Csharp/CSharp Tutorial/Data Structure/ArrayList

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Содержание

ArrayList: AddRange

using System;
using System.Collections;
using System.Collections.Specialized;
class MyClass{
   public string MyName="";   
}
class MainClass
{
  static void Main(string[] args)
  {
    ArrayList classList = new ArrayList();
    classList.AddRange(new MyClass[] { new MyClass(), 
                                           new MyClass(), 
                                           new MyClass()});
    Console.WriteLine("Items in List: {0}", classList.Count);
    // Print out current values. 
    foreach(MyClass c in classList)
    {
      Console.WriteLine("MyClass name: {0}", c.MyName);  
    }
  }
}
Items in List: 3
MyClass name:
MyClass name:
MyClass name:

ArrayList Query

using System;
using System.Collections;
using System.ruponentModel;
    public class Product
    {
        string name;
        public string Name
        {
            get { return name; }
        }
        decimal price;
        public decimal Price
        {
            get { return price; }
        }
        public Product(string name, decimal price)
        {
            this.name = name;
            this.price = price;
        }
        public static ArrayList GetSampleProducts()
        {
            ArrayList list = new ArrayList();
            list.Add(new Product("C", 9.99m));
            list.Add(new Product("A", 1.99m));
            list.Add(new Product("F", 2.99m));
            list.Add(new Product("S", 3.99m));
            return list;
        }
        public override string ToString()
        {
            return string.Format("{0}: {1}", name, price);
        }
    }
    class ArrayListSort
    {
        class ProductNameComparer : IComparer
        {
            public int Compare(object x, object y)
            {
                Product first = (Product)x;
                Product second = (Product)y;
                return first.Name.rupareTo(second.Name);
            }
        }
        static void Main()
        {
            ArrayList products = Product.GetSampleProducts();
            products.Sort(new ProductNameComparer());
            foreach (Product product in products)
            {
                Console.WriteLine(product);
            }
        }
    }

Box ints into ArrayList

using System;
using System.Collections;
class MainClass
{
  static void Main(string[] args)
  {    
    ArrayList myInts = new ArrayList();
    myInts.Add(8);
    myInts.Add(3);
    myInts.Add(9);
    // Unbox first item.
    int firstItem = (int)myInts[0];
    // Another boxing operation!
    Console.WriteLine("First item is {0}", firstItem);
  }
}
First item is 8

Capacity and element count

using System; 
using System.Collections; 
 
class MainClass { 
  public static void Main() { 
    ArrayList al = new ArrayList(); 
     
    Console.WriteLine("Adding 6 elements"); 
    al.Add("C"); 
    al.Add("A"); 
    al.Add("E"); 
    al.Add("B"); 
    al.Add("D"); 
    al.Add("F"); 
 
    Console.WriteLine("Add enough elements to force ArrayList to grow. Adding 20 more elements"); 
    
    for(int i=0; i < 20; i++) 
      al.Add((char)("a" + i)); 
    Console.WriteLine("Current capacity: " + 
                       al.Capacity); 
    Console.WriteLine("Number of elements after adding 20: " + 
                       al.Count); 
    Console.Write("Contents: "); 
    foreach(char c in al) 
      Console.Write(c + " "); 
    Console.WriteLine("\n"); 
  }
}
Adding 6 elements
Add enough elements to force ArrayList to grow. Adding 20 more elements
Current capacity: 32
Number of elements after adding 20: 26
Contents: C A E B D F a b c d e f g h i j k l m n o p q r s t

Change contents using array indexing

using System; 
using System.Collections; 
 
class MainClass { 
  public static void Main() { 
    ArrayList al = new ArrayList(); 
     
    Console.WriteLine("Adding 6 elements"); 
    // Add elements to the array list 
    al.Add("C"); 
    al.Add("A"); 
    al.Add("E"); 
    al.Add("B"); 
    al.Add("D"); 
    al.Add("F"); 
 
    // 
    Console.WriteLine("Change first three elements"); 
    al[0] = "X"; 
    al[1] = "Y"; 
    al[2] = "Z"; 
    Console.Write("Contents: "); 
    foreach(char c in al) 
      Console.Write(c + " "); 
    Console.WriteLine(); 
  } 
}
Adding 6 elements
Change first three elements
Contents: X Y Z B D F

Clear an ArrayList

using System;
using System.Collections;
class MainClass
{
  static void Main(string[] args)
  {
    ArrayList a = new ArrayList(10);
    int x = 0;
    a.Add( ++x);
    a.Add( ++x);
    a.Add( ++x);
    a.Add( ++x);
    a.Remove(x);
    
    a.RemoveAt(0);
    a.Clear();
  }
}

Create a string array and use the ICollection.CopyTo method to copy the contents of the ArrayList

using System;
using System.Collections;
class MainClass
{
    public static void Main(string[] args)
    {
        // Create a new ArrayList and populate it.
        ArrayList list = new ArrayList(5);
        list.Add("B");
        list.Add("G");
        list.Add("J");
        list.Add("S");
        list.Add("M");
        
        string[] array1 = new string[list.Count];
        list.CopyTo(array1, 0);
        Console.WriteLine("Array 1:");
        foreach (string s in array1) 
        { 
            Console.WriteLine("\t{0}",s); 
        }
    
    }
}
Array 1:
        B
        G
        J
        S
        M

Filter int from ArrayList

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Linq;
using System.Linq;
using System.Collections;
    class Car
    {
        public string PetName;
        public string Color;
        public int Speed;
        public string Make;
    }
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList myStuff = new ArrayList();
            myStuff.AddRange(new object[] { 10, 400, 8, false, new Car(), "string data" });
            IEnumerable<int> myInts = myStuff.OfType<int>();
            
            foreach (int i in myInts)
            {
                Console.WriteLine("Int value: {0}", i);
            }
        }
    }

Get an enumerator using the GetEnumerator() method and use it to read the elements in ArrayList

using System;
using System.Collections;
class MainClass
{
  public static void Main()
  {
    ArrayList myArrayList = new ArrayList();
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    
    string[] anotherStringArray = {"Here"s", "some", "more", "text"};
    myArrayList.SetRange(0, anotherStringArray);
    Console.WriteLine("Using the GetEnumerator() method to get an enumerator");
    IEnumerator myEnumerator = myArrayList.GetEnumerator();
    while (myEnumerator.MoveNext())
    {
      Console.WriteLine("myEnumerator.Current = " + myEnumerator.Current);
    }
  }
}

Get the number of elements

using System; 
using System.Collections; 
 
class MainClass { 
  public static void Main() { 
    ArrayList al = new ArrayList(); 
     
    Console.WriteLine("Initial number of elements: " + al.Count); 
 
    Console.WriteLine("Adding 6 elements"); 
    // Add elements to the array list 
    al.Add("C"); 
    al.Add("A"); 
    al.Add("E"); 
    al.Add("B"); 
    al.Add("D"); 
    al.Add("F"); 
 
    Console.WriteLine("Number of elements: " + al.Count); 
  }
}
Initial number of elements: 0
Adding 6 elements
Number of elements: 6

Insert(), AddRange(), and InsertRange() methods

using System;
using System.Collections;
class MainClass
{
  public static void Main()
  {
    ArrayList myArrayList = new ArrayList();
    
    myArrayList.Add("is");
    myArrayList.Insert(1, "is");
    string[] myStringArray = {"a", "test"};
    myArrayList.AddRange(myStringArray);
    string[] anotherStringArray = {"Here"s", "some", "more", "text"};
    myArrayList.InsertRange(myArrayList.Count, anotherStringArray);
    DisplayArrayList("myArrayList", myArrayList);
  }
  public static void DisplayArrayList(string arrayListName, ArrayList myArrayList)
  {
    for (int i = 0; i < myArrayList.Count; i++){
      Console.WriteLine(arrayListName + "[" + i + "] = " +
        myArrayList[i]);
    }
  }
  
}
myArrayList[0] = is
myArrayList[1] = is
myArrayList[2] = a
myArrayList[3] = test
myArrayList[4] = Here"s
myArrayList[5] = some
myArrayList[6] = more
myArrayList[7] = text

Insert and remove at specific index

using System;
using System.Collections;
class MainClass
{
  static void Main(string[] args)
  {
    ArrayList a = new ArrayList(10);
    int x = 0;
    a.Add( ++x);
    a.Add( ++x);
    a.Add( ++x);

    a.Remove(x);
    
    a.RemoveAt(0);
  }
}

Insert item to ArrayList by index

using System;
using System.Collections;
using System.Collections.Specialized;
class MyClass{
   public string MyName="";   
}
class MainClass
{
  static void Main(string[] args)
  {
    ArrayList classList = new ArrayList();
    classList.AddRange(new MyClass[] { new MyClass(), 
                                           new MyClass(), 
                                           new MyClass()});
    Console.WriteLine("Items in List: {0}", classList.Count);
    classList.Insert(2, new MyClass());
    Console.WriteLine("Items in classList: {0}", classList.Count);
    // Print out current values. 
    foreach(MyClass c in classList)
    {
      Console.WriteLine("MyClass name: {0}", c.MyName);  
    }
  }
}
Items in List: 3
Items in classList: 4
MyClass name:
MyClass name:
MyClass name:
MyClass name:

IsFixedSize and IsReadOnly properties

using System;
using System.Collections;
class MainClass
{
  public static void Main()
  {
    ArrayList myArrayList = new ArrayList();
    
    Console.WriteLine("myArrayList.IsFixedSize = " + myArrayList.IsFixedSize);
    Console.WriteLine("myArrayList.IsReadOnly = " + myArrayList.IsReadOnly);
  }
}
myArrayList.IsFixedSize = False
myArrayList.IsReadOnly = False

Make an ArrayList Synchronized

using System;
using System.Collections;
class MainClass
{
  static void Main(string[] args)
  {
    ArrayList a = new ArrayList(10);
    ArrayList.Synchronized(a);
  }
}

Re-enumerate the list

using System; 
using System.Collections; 
 
class MainClass {  
  public static void Main() { 
    ArrayList list = new ArrayList(1); 
 
    for(int i=0; i < 10; i++) 
      list.Add(i); 
 
    IEnumerator etr = list.GetEnumerator(); 
    while(etr.MoveNext())  
      Console.Write(etr.Current + " "); 
 
    Console.WriteLine(); 
 
     
    etr.Reset(); 
    while(etr.MoveNext())  
      Console.Write(etr.Current + " "); 
 
    Console.WriteLine(); 
  } 
}
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9

Remove element 0, first "text" element, and two elements starting at index 3

using System;
using System.Collections;
class MainClass
{
  public static void Main()
  {
    ArrayList myArrayList = new ArrayList();
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    
    string[] anotherStringArray = {"Here"s", "some", "more", "text"};
    myArrayList.SetRange(0, anotherStringArray);

    myArrayList.RemoveAt(0);
    myArrayList.Remove("text");
    myArrayList.RemoveRange(3, 2);
    DisplayArrayList("myArrayList", myArrayList);
  }
  public static void DisplayArrayList(string arrayListName, ArrayList myArrayList)
  {
    for (int i = 0; i < myArrayList.Count; i++){
      Console.WriteLine(arrayListName + "[" + i + "] = " +
        myArrayList[i]);
    }
  }
}

Remove elements from ArrayList

using System; 
using System.Collections; 
 
class MainClass { 
  public static void Main() { 
    ArrayList al = new ArrayList(); 
     
    Console.WriteLine("Adding 6 elements"); 
    // Add elements to the array list 
    al.Add("C"); 
    al.Add("A"); 
    al.Add("E"); 
    al.Add("B"); 
    al.Add("D"); 
    al.Add("F"); 
 
    Console.WriteLine("Removing 2 elements"); 
    // Remove elements from the array list. 
    al.Remove("F"); 
    al.Remove("A"); 
 
    Console.WriteLine("Number of elements: " + 
                       al.Count); 
  }
}
Adding 6 elements
Removing 2 elements
Number of elements: 4

Sort and search an ArrayList

using System; 
using System.Collections; 
 
class MainClass { 
  public static void Main() { 
    // create an array list 
    ArrayList al = new ArrayList(); 
     
    // Add elements to the array list 
    al.Add(155); 
    al.Add(413); 
    al.Add(-41); 
    al.Add(818); 
    al.Add(31); 
    al.Add(191); 
 
    Console.Write("Original contents: "); 
    foreach(int i in al) 
      Console.Write(i + " "); 
    Console.WriteLine("\n"); 
 
    // Sort 
    al.Sort(); 
 
    // Use foreach loop to display the list. 
    Console.Write("Contents after sorting: "); 
    foreach(int i in al) 
      Console.Write(i + " "); 
    Console.WriteLine("\n"); 
 
    Console.WriteLine("Index of 413 is " + al.BinarySearch(413)); 
  } 
}
Original contents: 155 413 -41 818 31 191
Contents after sorting: -41 31 155 191 413 818
Index of 413 is 4

Use ArrayList copy constructor

using System;
using System.Collections;
class MainClass
{
  public static void Main()
  {
    ArrayList myArrayList = new ArrayList();
    myArrayList.Add("This");
    myArrayList.Add("is");
    myArrayList.Add("a");
    myArrayList.Add("test");
    ArrayList anotherArrayList = new ArrayList(myArrayList);
    Console.WriteLine(anotherArrayList);
  }
}

Use ArrayList.ToArray to create an object array from the contents of the collection

using System;
using System.Collections;
class MainClass
{
    public static void Main(string[] args)
    {
        // Create a new ArrayList and populate it.
        ArrayList list = new ArrayList(5);
        list.Add("B");
        list.Add("G");
        list.Add("J");
        list.Add("S");
        list.Add("M");
        object[] array2 = list.ToArray();
        Console.WriteLine("Array 2:");
        foreach (string s in array2) 
        {
            Console.WriteLine("\t{0}", s);
        }
    
    }
}
Array 2:
        B
        G
        J
        S
        M

Use enumerator to access list

using System; 
using System.Collections; 
 
class MainClass {  
  public static void Main() { 
    ArrayList list = new ArrayList(1); 
 
    for(int i=0; i < 10; i++) 
      list.Add(i); 
 
    IEnumerator etr = list.GetEnumerator(); 
    while(etr.MoveNext())  
      Console.Write(etr.Current + " "); 
 
    Console.WriteLine(); 
 
  } 
}
0 1 2 3 4 5 6 7 8 9

Use the Contains() method to determine if the string "text" is in the ArrayList

using System;
using System.Collections;
class MainClass
{
  public static void Main()
  {
    ArrayList myArrayList = new ArrayList();
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    
    string[] anotherStringArray = {"Here"s", "some", "more", "text"};
    myArrayList.SetRange(0, anotherStringArray);

    if (myArrayList.Contains("text"))
    {
      int index = myArrayList.IndexOf("text");
      Console.WriteLine("myArrayList does contain the word "text"");
      Console.WriteLine(""text" first occurs at index " + index);
      index = myArrayList.LastIndexOf("text");
      Console.WriteLine(""text" last occurs at index " + index);
    }
  }
}

Use the IndexOf() and LastIndexOf() methods to display the first and last occurrence

using System;
using System.Collections;
class MainClass
{
  public static void Main()
  {
    ArrayList myArrayList = new ArrayList();
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    
    string[] anotherStringArray = {"Here"s", "some", "more", "text"};
    myArrayList.SetRange(0, anotherStringArray);

    if (myArrayList.Contains("text"))
    {
      int index = myArrayList.IndexOf("text");
      Console.WriteLine("myArrayList does contain the word "text"");
      Console.WriteLine(""text" first occurs at index " + index);
      index = myArrayList.LastIndexOf("text");
      Console.WriteLine(""text" last occurs at index " + index);
    }
  }
}

Use the Reset() method and access the first row again using MoveNext()

using System;
using System.Collections;
class MainClass
{
  public static void Main()
  {
    ArrayList myArrayList = new ArrayList();
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    
    string[] anotherStringArray = {"Here"s", "some", "more", "text"};
    myArrayList.SetRange(0, anotherStringArray);
    Console.WriteLine("Using the GetEnumerator() method to get an enumerator");
    IEnumerator myEnumerator = myArrayList.GetEnumerator();
    while (myEnumerator.MoveNext())
    {
      Console.WriteLine("myEnumerator.Current = " + myEnumerator.Current);
    }
    myEnumerator.Reset();
    myEnumerator.MoveNext();
    Console.WriteLine("myEnumerator.Current = " + myEnumerator.Current);
    
  }
}

Use the Reverse() method to reverse myArrayList

using System;
using System.Collections;
class MainClass
{
  public static void Main()
  {
    ArrayList myArrayList = new ArrayList();
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    
    string[] anotherStringArray = {"Here"s", "some", "more", "text"};
    myArrayList.SetRange(0, anotherStringArray);
    myArrayList.Reverse();
    DisplayArrayList("myArrayList", myArrayList);
  }
  public static void DisplayArrayList(string arrayListName, ArrayList myArrayList)
  {
    for (int i = 0; i < myArrayList.Count; i++){
      Console.WriteLine(arrayListName + "[" + i + "] = " +
        myArrayList[i]);
    }
  }
}

Use the SetRange() method to copy the elements from anotherStringArray to myArrayList, starting at index 0

using System;
using System.Collections;
class MainClass
{
  public static void Main()
  {
    ArrayList myArrayList = new ArrayList();
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    string[] anotherStringArray = {"Here"s", "some", "more", "text"};
    myArrayList.SetRange(0, anotherStringArray);

    DisplayArrayList("myArrayList", myArrayList);
  }
  public static void DisplayArrayList(string arrayListName, ArrayList myArrayList)
  {
    for (int i = 0; i < myArrayList.Count; i++){
      Console.WriteLine(arrayListName + "[" + i + "] = " +
        myArrayList[i]);
    }
  }
  
}

Using the GetRange() method to get two elements from myArrayList, starting at index 1

using System;
using System.Collections;
class MainClass
{
  public static void Main()
  {
    ArrayList myArrayList = new ArrayList();
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    
    string[] anotherStringArray = {"Here"s", "some", "more", "text"};
    myArrayList.SetRange(0, anotherStringArray);
    ArrayList anotherArrayList = myArrayList.GetRange(1, 2);
    DisplayArrayList("anotherArrayList", anotherArrayList);
  }
  public static void DisplayArrayList(string arrayListName, ArrayList myArrayList)
  {
    for (int i = 0; i < myArrayList.Count; i++){
      Console.WriteLine(arrayListName + "[" + i + "] = " +
        myArrayList[i]);
    }
  }
}

Using the TrimToSize() method to reduce the capacity of ArrayList

using System;
using System.Collections;
class MainClass
{
  public static void Main()
  {
    ArrayList myArrayList = new ArrayList();
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    
    string[] anotherStringArray = {"Here"s", "some", "more", "text"};
    myArrayList.SetRange(0, anotherStringArray);
    myArrayList.TrimToSize();
    Console.WriteLine("myArrayList.Capacity = " + myArrayList.Capacity);
  }
}