どうも、ちょげ(@chogetarou)です。
List(リスト)の重複を削除する方法を紹介します。
方法

List(リスト)の重複を削除する方法は、2つあります。
HashSet
1つは、HashSetを使う方法です。
まず、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);
}
}
}
Distinct()
もう1つは、Distinct()を使う方法です。
まず、System.Linqを導入します。
using System.Linq;
そして、リスト(List)からDistinct()を呼び出します。
Distinct()からToList()を呼び出します。
var unique = list.Distinct().ToList();
上記のToList()は、Distinct()を呼び出したリスト(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 = numbers.Distinct().ToList();
foreach(var i in unique)
{
Console.WriteLine(i);
}
}
}
まとめ
List(リスト)の重複を削除する方法は、次の2つです。
- HashSetを使う方法
- Distinct()を使う方法
コメント