どうも、ちょげ(@chogetarou)です。
HashSet<T>を使って、リスト(List)の重複する要素を削除する方法を紹介します。
方法

HashSet<T>を使って、リスト(List)の重複する要素を削除するには、System.Linqを使います。
まず、System.Linqを導入します。
using System.Linq;
次に、HashSetをインスタンス化します。
インスタンス化する際、引数にリストを指定します。
そして、HashSetのインスタンスからToList()を呼び出します。
var unique = new HashSet<T>(list).ToList();
上記のToList()は、HashSet()の引数に指定したリスト(List)の重複を削除した新しいリストを生成します。
使用例
using System;
using System.Linq;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
List<int> numbers = new List<int>() { 1, 2, 1, 1, 3, 2, 3};
List<int> unique = new HashSet<int>(numbers).ToList();
foreach(var i in unique)
{
Console.WriteLine(i);
}
}
}

コメント