第二十二章データアクセス(In.net 4.5)の集合

16969 ワード

1.概要
この章の内容は.Netプラットフォームのコレクション、コレクションの選択方法、カスタムコレクションの実装方法.
2.主な内容
2.1配列の使用(Array)
int[] arrayOfInt = new int[10]; for (int x = 0; x < arrayOfInt.Length; x++) {     arrayOfInt[x] = x; } foreach (int i in arrayOfInt) //   IEnumerable {     Console.Write(i); // Displays 0123456789 

}

    .Netでは多次元配列とジグザグ配列もサポートされています
string[,] array2D = new string[32] { { “one”, “two” }, { “three”, “four” },                         { “five”, “six” } }; int[][] jaggedArray =     {         new int[] {1,3,5,7,9},         new int[] {0,2,4,6},         new int[] {42,21}     };

2.2汎用バージョンと非汎用バージョンの理解
*汎用パラメータとして値タイプを使用する場合は、発生する可能性のある梱包に注意してください.たとえば、値タイプがIEquatableまたはIComparableを実装していない場合.
2.3使用リスト(List)
Listの定義:
public class List<T> : IList<T>, ICollection<T>, IList, ICollection,  IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable

ここでIListとICollectionの定義は以下の通りである.
public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable {         T this[int index] { getset; }         int IndexOf(T item); void Insert(int index, T item);             void RemoveAt(int index); } public interface ICollection<T> : IEnumerable<T>, IEnumerable {         int Count { get; }             bool IsReadOnly { get; }         void Add(T item);             void Clear();             bool Contains(T item);             void CopyTo(T[] array, int arrayIndex);             bool Remove(T item); }

次に、Listを使用してデータ項目を操作する例を示します.
List<string> listOfStrings =     new List<string> { “A”, “B”, “C”, “D”, “E” }; for (int x = 0; x < listOfStrings.Count; x++)     Console.Write(listOfStrings[x]); // Displays: ABCDE 

 listOfStrings.Remove(“A”); Console.WriteLine(listOfStrings[0]); // Displays: B 

 listOfStrings.Add(“F”); Console.WriteLine(listOfStrings.Count); // Displays: 5 

 

bool hasC = listOfStrings.Contains(“C”); Console.WriteLine(hasC); // Displays: true

2.4ディクショナリの使用(Dictionary)
辞書はキー値ペアで構成されており、キーに基づいて値を取得できます.重複するキーは許可されていません.辞書の定義:
public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IReadOnlyDictionary<TKey, TValue>, IReadOnlyCollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable, ISerializable, IDeserializationCallback

辞書の使用例:
Person p1 = new Person { Id = 1, Name = “Name1” }; Person p2 new Person { Id = 2, Name = “Name2” }; Person p3 new Person { Id = 3, Name = “Name3” }; var dict = new Dictionary<int, Person>(); dict.Add(p1.Id, p1); dict.Add(p2.Id, p2); dict.Add(p3.Id, p3); foreach (KeyValuePair<int, Person> v in dict) {     Console.WriteLine(“{0}: {1}”, v.Key, v.Value.Name); } dict[0] = new Person { Id = 4, Name = “Name4” }; Person result; if (!dict.TryGetValue(5out result)) {     Console.WriteLine(“No person with a key of 5 can be found”); }

2.5使用セット(sets)
setsは非繰返しで無秩序な集合である.C#のsetはシステム保持キーワードであり、ISetを実現するHastSetを使用することができる.
public interface ISet<T> : ICollection<T>, IEnumerable<T>, IEnumerable { bool Add(T item); void ExceptWith(IEnumerable<T> other); void IntersectWith(IEnumerable<T> other); bool IsProperSubsetOf(IEnumerable<T> other); bool IsProperSupersetOf(IEnumerable<T> other); bool IsSubsetOf(IEnumerable<T> other); bool IsSupersetOf(IEnumerable<T> other); bool Overlaps(IEnumerable<T> other); bool SetEquals(IEnumerable<T> other); void SymmetricExceptWith(IEnumerable<T> other); void UnionWith(IEnumerable<T> other); }

HashSetを使用する例:
public void UseHashSet() {     HashSet<int> oddSet = new HashSet<int>();     HashSet<int> evenSet = new HashSet<int>();     for (int x = 1; x <= 10; x++)     {         if (x % 2 == 0)             evenSet.Add(x);         else             oddSet.Add(x);     }     DisplaySet(oddSet);     DisplaySet(evenSet);     oddSet.UnionWith(evenSet);     DisplaySet(oddSet); } private void DisplaySet(HashSet<intset) {     Console.Write(“{“);     foreach (int i in set)     {         Console.Write(“ {0}”, i);     }     Console.WriteLine(“ }”); }

2.6キューとスタックの使用
キューは主に一時的にデータを格納するために使用され、先進的な先出しの原則に従います.3つの重要な方法は、Enqueue、Dequeue、Peekです.
Queue<string> myQueue = new Queue<string>(); myQueue.Enqueue(“Hello”); myQueue.Enqueue(“World”); myQueue.Enqueue(“From”); myQueue.Enqueue(“A”); myQueue.Enqueue(“Queue”); foreach (string s in myQueue)     Console.Write(s + “ “); // Displays: Hello World From A Queue

スタックは先進的な後出の原則に従う.Push、Pop、Peekの3つの方法がキューに似ています.
Stack<string> myStack = new Stack<string>(); myStack.Push(“Hello”); myStack.Push(“World”); myStack.Push(“From”); myStack.Push(“A”); myStack.Push(“Queue”); foreach (string s in myStack)     Console.Write(s + “ “); // Displays: Queue A From World Hello

2.7適切な集合の選択
各コレクション間の最大の違いは、要素へのアクセス方法です.
①リストと辞書は、要素のランダムアクセスをサポートします.ディクショナリでは、エレメントの読み取り速度が速くなりますが、重複するデータ・アイテムは保存できません.
②キューとスタックは、特定の順序の要素アクセス方式を提供します.要素を取り出すと自動的にコレクションから削除されます.
③Setの集合に基づいて、要素比較においていくつかの特性がある.ただし、要素のランダムアクセスは提供されません.
2.8カスタムコレクションの作成
    .Netが提供する集合関連インタフェースには、IEnumerable、IEnumerable、IList、ICollection、IDictionary
    ICollection、ISet.
既存のコレクションオブジェクトを継承してカスタムメソッドを追加することもできます.
public class PeopleCollection : List<Person> {     public void RemoveByAge(int age)     {         for (int index = this.Count - 1; index >= 0; index--)         {             if (this[index].Age == age)             {                 this.RemoveAt(index);             }         }     }     public override string ToString()     {         StringBuilder sb new StringBuilder();         foreach (Person p in this)         {             sb.AppendFormat(“{0} {1is {2}”, p.FirstName, p.LastName, p.Age);         }         return sb.ToString();     } }

3.まとめ
  ① .Netは汎用と非汎用の集合バージョンを提供し,使用する場合は汎用バージョンを優先的に選択する.
②配列(Array)は最も基本的な集合であり,定長である.
③リスト(List)は最も多く用いられる集合であり,長くなる.
④ディクショナリ(Dictionary)は、アクセスキー値ペアの集合である.
⑤HashSetは、一意のアイテムを保存し、対応するアクションを提供します.
⑥キューは先出しの集合です.
⑦スタックは先進後出の集合です.
⑧指定したインタフェースを実装したり、既存のコレクションを継承したりすることで、コレクションタイプをカスタマイズできます.