LoginSignup
9
9

More than 5 years have passed since last update.

【Unity】Listや配列で要素の重複を確認したいときはHashSetが使える!

Last updated at Posted at 2018-02-28

※コメントに丁寧な解説を頂いているので是非そちらも参照ください。
C#でListや配列の重複を確認したくなったことはありませんか?
そんなときはHashSet型が便利です!

HashSetは重複した要素を格納できないので、Listや配列に重複があるかどうかを判定するのに使えます。

自分はポケモン対戦風のゲームを開発していて、ポケモン対戦では同じパーティーに同じポケモンを入れられないルールが主流なので、ポケモンの重複チェックが必要でこの方法を使いました。

CheckDuplication

using System.Collections;
using System.Collections.Generic;

List<Pokemon> Party = new List<Pokemon>();

//重複時はfalseを返す
bool CheckDuplication()
{
    HashSet<Pokemon> hashSet = new HashSet<Pokemon> ();

    foreach (var item in Party) {
        hashSet.Add (item);
    }

    //重複がある場合は要素数が減る
    if (Party.Count > hashSet.Count) {
        return false;
    }
        return true;
}

*注記
ちなみにLINQを使うとGroupByでもっと簡単に書けるみたいです。

9
9
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9