ソースレビューしていたら、List使うだろーと思っていたところでHashSetを使われていることがありました。
なぜにHashSet? そもそもHashSetってなに?と調べてみたところ……。
圧倒的にListよりHashSetの方が検索速度が速いことを初めて知りました。
では、HashSetとListの違いとはなんでしょう?
MSDNからHashSetの特徴をざっくり言うと
- 高パフォーマンスの set 操作を行える
- 重複したデータは持たない
- 特定の順序はない
Listに比べてパフォーマンスは高いが、重複したデータは持たせることが出来ないといったところでしょうか。
重複したデータを持つことがないのであればHashSetを使った方が良いということなので、頭の片隅には置いておこうと思います。
using System; using System.Collections.Generic; using System.Linq; namespace HashSetTraining { class Program { static void Main(string[] args) { HashSet<int> hashSet = new HashSet<int>() {9, 1, 2}; hashSet.Add(-3); hashSet.Remove(3); // hashSet.RemoveAt(0); Compile Error(HashSet don't have RemoveAt) hashSet.Add(2); // Cannot Add Duplicated Value Console.WriteLine(string.Join(',' ,hashSet.OrderByDescending(i => i))); // result 9,2,1,-3 } } }