2008年9月24日水曜日

C# Dictionaryの使い方

//
Dictionary openWith = new Dictionary();

// Dictionaryに要素を追加する。
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("rtf", "wordpad.exe");

// もしも新しいキーがDictionaryに存在していたら、Addメソッドは例外を投げる
try
{
    openWith.Add("txt", "winword.exe");

}catch (ArgumentException)
{
    Console.WriteLine("An element with Key = \"txt\" already exists.");
}

// キーが存在していても、上書きが出来る。
openWith["rtf"] = "winword.exe";

// 存在していないキーを指定したら、例外が発生する。
try
{

openWith["tif"];

}catch(KeyNotFoundException)
{
}

C# list型の使い方

//
List dinosaurs = new List();


// listに要素を追加する
dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");


// listの現在の容量
dinosaurs.Capacity;


// listの現在の要素数
dinosaurs.Count;

// 要素の中に"Deinonychus"が含まれていないのでFalseが返ってくる
dinosaurs.Contains("Deinonychus"));


// 2番目の要素に挿入
dinosaurs.Insert(2, "Compsognathus);

// 要素の"Compsognathus"を削除する
dinosaurs.Remove("Compsognathus");

// 要素は全て削除。容量はそのまま残る
dinosaurs.Clear();

2008年9月23日火曜日

C# stack型の使い方

Stack numbers = new Stack();

// 要素追加
numbers.Push("one");
numbers.Push("two");

// 要素の取り出し
numbers.Pop()

// スタックのコピー
Stack stack2 = new Stack(numbers.ToArray());

// numbers.Countはstackの要素数を数える。
string[] array2 = new string[numbers.Count * 2];

// array2 にコピーします。
numbers.CopyTo(array2, numbers.Count);

// コンストラクタでarray2をarray3にコピー
Stack stack3 = new Stack(array2);

// "four"の要素がないからFalseを返す
stack2.Contains("four"));