7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【C#】【自分用メモ】List内の重複チェック

Posted at

【目標】
Listで重複チェックをし、被っているものを表示させてくれる仕組みを作りたい。

【その1】
順当にFor文で回す。

Hoge.cs
using System;

class Hoge
{
  static void Main()
  {
    // リスト
    string[] berries = new string[]{"blackberry", "blueberry", "strawberry", "cranberry", "raspberry", "blueberry"};

    for (int i = 0; i < berries.Count - 1; i++)
    {
      for (int j = i + 1; j < berries.Count; j++)
      {
        if (berries[i].Equals(berries[j]))
        {
           Console.WriteLine("{0}は重複しています。", berries[j]);
           break;
        }
      }
    }

  }
}

まぁなんとネストが深いことやら…。

【その2】
そこでHashSetの出番です。
こちらを参照にさせてもらいました。

Hoge.cs
using System;
using System.Collections.Generic;

class Hoge
{
  static void Main()
  {
    // リスト
    string[] berries = new string[]{"blackberry", "blueberry", "strawberry", "cranberry", "raspberry", "blueberry"};

    var hashset = new HashSet<string>();
    foreach(var berry in berries)
    {
      if (hashset.Add(berry) == false)
      {
        Console.WriteLine("{0}は重複しています。", berry);
        break;
      }
    }

  }
}

以上、備忘録でした。

7
5
4

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
7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?