C#でのリストとHashSet間の変換
この投稿では、C#でリストをHashSetに、またはその逆に変換する方法について説明します。
変換 List
に HashSet
:
1.使用する HashSet
コンストラクタ
使用できます HashSetコンストラクター、 IEnumerable<T>
の新しいインスタンスを構築するには HashSet<T>
リストの個別の要素を含むクラス。
以来注意してください HashSet
個別の要素が含まれている場合、リスト内の繰り返される要素はすべて破棄されます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> list = new List<int> { 1, 3, 3, 2, 4 }; HashSet<int> set = new HashSet<int>(list); Console.WriteLine(String.Join(",", set)); } } /* 出力: 1,3,2,4 */ |
2. Enumerable.ToHashSet()
方法 (System.Linq
)
使用できます ToHashSet() を作成する方法 HashSet<T>
から IEnumerable<T>
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> list = new List<int> { 1, 3, 3, 2, 4 }; HashSet<int> set = list.ToHashSet(); Console.WriteLine(String.Join(",", set)); } } /* 出力: 1,3,2,4 */ |
変換 HashSet
に List
:
1.使用する List
コンストラクタ
使用できます List
コンストラクター、 IEnumerable<T>
の新しいインスタンスを構築するには List<T>
セットのすべての要素が含まれています。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Collections.Generic; public class Example { public static void Main() { HashSet<int> set = new HashSet<int> { 1, 2, 3, 4, 5 }; List<int> list = new List<int>(set); Console.WriteLine(String.Join(",", list)); } } /* 出力: 1,2,3,4,5 */ |
2. Enumerable.ToList()
方法 (System.Linq
)
使用できます ToList() を作成する方法 List<T>
から IEnumerable<T>
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Collections.Generic; using System.Linq; public class Example { public static void Main() { HashSet<int> set = new HashSet<int> { 1, 2, 3, 4, 5 }; List<int> list = set.ToList(); Console.WriteLine(String.Join(",", list)); } } /* 出力: 1,2,3,4,5 */ |
C#でのListとHashSet間の変換については以上です。