程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> Collections of Objects 對象群集

Collections of Objects 對象群集

編輯:C#入門知識

定義:能在對象被創建時將他們收集在一起,作為一個群組來管理和進行整體操作,並且在需要的時候還能單獨引用他們中的一個。

1:簡單的群集——數組

  遍歷數組

  for(int i=0;i<=99;i++){

    if(studentBody[i] != null){//避開地雷

      Console.WriteLine(studentBody[i].GetName());

    }

  }

2:有序列表

2.1有序列表和數組類似,但其中存儲的項是以某種特定順序放置的,在獲取值的時候也按這種順序取得,當新項被插入時,有序列表自動增加長度。(ArrayList)

using System;
using System.Collections;
public class SamplesArrayList  {

   public static void Main()  {

      // Creates and initializes a new ArrayList.
      ArrayList myAL = new ArrayList();
      myAL.Add("Hello");
      myAL.Add("World");
      myAL.Add("!");

      // Displays the properties and values of the ArrayList.
      Console.WriteLine( "myAL" );
      Console.WriteLine( "    Count:    {0}", myAL.Count );
      Console.WriteLine( "    Capacity: {0}", myAL.Capacity );
      Console.Write( "    Values:" );
      PrintValues( myAL );
   }

   public static void PrintValues( IEnumerable myList )  {
      foreach ( Object obj in myList )
         Console.Write( "   {0}", obj );
      Console.WriteLine();
   }

}


/*
This code produces output similar to the following:

myAL
    Count:    3
    Capacity: 4
    Values:   Hello   World   !

*/

2.2分類有序列表(是一種特殊的有序列表,普通的有序列表把新加入的對象自動添加到列表末尾,而分類有序列表把新加入的對象插入到列表的適當位置,以維持分類列表的分類排序,

             對於分類有序列表我們必須定義對象的分類排序依據即定義一個分類鍵,典型的時SortedList.表示鍵/值對的集合,這些鍵值對按鍵排序並可按照鍵和索引訪問。)


using System;
using System.Collections;
public class SamplesSortedList  {

   public static void Main()  {

      // Creates and initializes a new SortedList.
      SortedList mySL = new SortedList();
       mySL.Add("Third", "!");
       mySL.Add("Second", "World");
       mySL.Add("First", "Hello");

      // Displays the properties and values of the SortedList.
      Console.WriteLine( "mySL" );
      Console.WriteLine( "  Count:    {0}", mySL.Count );
      Console.WriteLine( "  Capacity: {0}", mySL.Capacity );
      Console.WriteLine( "  Keys and Values:" );
      PrintKeysAndValues( mySL );
   }


   public static void PrintKeysAndValues( SortedList myList )  {
      Console.WriteLine( "\t-KEY-\t-VALUE-" );
      for ( int i = 0; i < myList.Count; i++ )  {
         Console.WriteLine( "\t{0}:\t{1}", myList.GetKey(i), myList.GetByIndex(i) );
      }
      Console.WriteLine();
   }
}
/*
This code produces the following output.

mySL
  Count:    3
  Capacity: 16
  Keys and Values:
    -KEY-    -VALUE-
    First:    Hello
    Second:    World
    Third:    !
*/

3:集合(是一種未排序的群集,也就是說在將新項插入的集合中後,無法通過位置索引訪問它)注意集合中不允許存在重復的對象引用但可以向有序列表中多次添加同一個對象。

4:字典(提供一種手段,讓對象引用被存儲時,同時存儲一個唯一的查詢鍵 典型的是Hashtable)


using System;
using System.Collections;

class Example
{
    public static void Main()
    {
        // Create a new hash table.
        //
        Hashtable openWith = new Hashtable();

        // Add some elements to the hash table. There are no
        // duplicate keys, but some of the values are duplicates.
        openWith.Add("txt", "notepad.exe");
        openWith.Add("bmp", "paint.exe");
        openWith.Add("dib", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");

        // The Add method throws an exception if the new key is
        // already in the hash table.
        try
        {
            openWith.Add("txt", "winword.exe");
        }
        catch
        {
            Console.WriteLine("An element with Key = \"txt\" already exists.");
        }

        // The Item property is the default property, so you
        // can omit its name when accessing elements.
        Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);

        // The default Item property can be used to change the value
        // associated with a key.
        openWith["rtf"] = "winword.exe";
        Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);

        // If a key does not exist, setting the default Item property
        // for that key adds a new key/value pair.
        openWith["doc"] = "winword.exe";

        // ContainsKey can be used to test keys before inserting
        // them.
        if (!openWith.ContainsKey("ht"))
        {
            openWith.Add("ht", "hypertrm.exe");
            Console.WriteLine("Value added for key = \"ht\": {0}", openWith["ht"]);
        }

        // When you use foreach to enumerate hash table elements,
        // the elements are retrieved as KeyValuePair objects.
        Console.WriteLine();
        foreach( DictionaryEntry de in openWith )
        {
            Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
        }

        // To get the values alone, use the Values property.
        ICollection valueColl = openWith.Values;

        // The elements of the ValueCollection are strongly typed
        // with the type that was specified for hash table values.
        Console.WriteLine();
        foreach( string s in valueColl )
        {
            Console.WriteLine("Value = {0}", s);
        }

        // To get the keys alone, use the Keys property.
        ICollection keyColl = openWith.Keys;

        // The elements of the KeyCollection are strongly typed
        // with the type that was specified for hash table keys.
        Console.WriteLine();
        foreach( string s in keyColl )
        {
            Console.WriteLine("Key = {0}", s);
        }

        // Use the Remove method to remove a key/value pair.
        Console.WriteLine("\nRemove(\"doc\")");
        openWith.Remove("doc");

        if (!openWith.ContainsKey("doc"))
        {
            Console.WriteLine("Key \"doc\" is not found.");
        }
    }
}

/* This code example produces the following output:

An element with Key = "txt" already exists.
For key = "rtf", value = wordpad.exe.
For key = "rtf", value = winword.exe.
Value added for key = "ht": hypertrm.exe

Key = dib, Value = paint.exe
Key = txt, Value = notepad.exe
Key = ht, Value = hypertrm.exe
Key = bmp, Value = paint.exe
Key = rtf, Value = winword.exe
Key = doc, Value = winword.exe

Value = paint.exe
Value = notepad.exe
Value = hypertrm.exe
Value = paint.exe
Value = winword.exe
Value = winword.exe

Key = dib
Key = txt
Key = ht
Key = bmp
Key = rtf
Key = doc

Remove("doc")
Key "doc" is not found.
 */
 

摘自  yikeshu
 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved