要素を重複なく管理するには?(HashSetクラス編)[3.5、C#、VB].NET TIPS

» 2008年06月19日 05時00分 公開
[遠藤孝信デジタルアドバンテージ]

この記事は会員限定です。会員登録(無料)すると全てご覧いただけます。

「.NET TIPS」のインデックス

連載目次

 何らかの要素(オブジェクト)を、重複を省いて一覧として保持したい場合がある。例えば、項目を重複なく処理するために、すでに処理済みの項目一覧を保持しておき、次に処理すべき項目がすでに一覧にあれば何もせず、なければ一覧に加えて処理を行うといった場合である。

.NET Framework 2.0ではDictionaryクラス

 上記のような処理は.NET Framework 2.0であれば、Dictionaryクラス(System.Collections.Generic名前空間)を使用するのが一般的であった(Dictionaryクラスについては「TIPS:ハッシュテーブル(連想配列)を使うには?(Dictionaryクラス編)」を参照)。

 次のコードは、英文中に現れる単語を重複せずに表示するサンプル・プログラムである。すでに表示した英単語をDictionaryクラスで管理している。

// dictionary.cs

using System;
using System.Collections.Generic;

class Program {
  static void Main() {

    string lincoln =
      "government of the people by the people for the people";

    // Dictionaryクラスによる単語テーブル
    Dictionary<string, object> dictTable
      = new Dictionary<string, object>();

    foreach (string word in lincoln.Split(' ')) {

      // 単語が未登録なら追加してから表示
      if (!dictTable.ContainsKey(word)) {
        dictTable.Add(word, null);
        Console.WriteLine(word);
      }
    }
    // 出力:
    // government
    // of
    // the
    // people
    // by
    // for

  }
}

// コンパイル方法:csc dictionary.cs

Dictionaryクラスを使用した単語の重複管理(C#)
dictionary.csのダウンロード

' dictionary.vb

Imports System
Imports System.Collections.Generic

Class Program
  Shared Sub Main()

    Dim lincoln As String = _
      "government of the people by the people for the people"

    ' Dictionaryクラスによる単語テーブル
    Dim dictTable As New Dictionary(Of String, Object)

    For Each word As String In lincoln.Split(" ")

      ' 単語が未登録なら追加してから表示
      If Not dictTable.ContainsKey(word) Then
        dictTable.Add(word, Nothing)
        Console.WriteLine(word)
      End If

    Next
    ' 出力:
    ' government
    ' of
    ' the
    ' people
    ' by
    ' for
  End Sub
End Class

' コンパイル方法:vbc dictionary.vb

Dictionaryクラスを使用した単語の重複管理(VB)
dictionary.vbのダウンロード

 Dictionaryクラスはキーと値のペアを、キーが重複しないように保持するが、本稿のような用途ではキーのみで用が足りるため、値の方は未使用となる(上記のコードではnull/Nothingを取りあえず入れている)。

.NET Framework 3.5ではHashSetクラス

Copyright© Digital Advantage Corp. All Rights Reserved.

RSSについて

アイティメディアIDについて

メールマガジン登録

@ITのメールマガジンは、 もちろん、すべて無料です。ぜひメールマガジンをご購読ください。