将数组转换为.NET中的HashSet <t> </t>

时间:2010-11-11 16:25:05

标签: c# .net

如何将数组转换为哈希集?

string[]  BlockedList = BlockList.Split(new char[] { ';' },     
StringSplitOptions.RemoveEmptyEntries);

我需要将此列表转换为hashset

7 个答案:

答案 0 :(得分:85)

您没有指定BlockedList的类型,因此我假设它是源自IList的内容(如果您想String,那么您编写BlockList然后它将是一个派生自IList)的字符串数组。

HashSet有一个带IEnumerable的构造函数,因此您只需将列表传递给此构造函数,因为IList派生自IEnumerable

var set = new HashSet(BlockedList);

答案 1 :(得分:15)

我假设BlockList是一个字符串(因此调用Split),它返回一个字符串数组。

只需将数组(实现IEnumerable)传递给constructor of the HashSet

var hashSet = new HashSet<string>(BlockedList);

答案 2 :(得分:9)

这是一个扩展方法,它将从任何IEnumerable生成HashSet:

public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
{
    return new HashSet<T>(source);
}

要与上面的例子一起使用:

var hashSet = BlockedList.ToHashSet();

答案 3 :(得分:2)

在扩展示例中错过了新关键字....

  public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
    {
        return new HashSet<T>(source);
    }

答案 4 :(得分:1)

开始使用.Net Framework 4.7.1和.Net Core 2.0 there is built-in ToHashSet方法

if(ret != 1) {
  /* Error handling */
 }

答案 5 :(得分:0)

为了更进一步,下面的单行演示了如何将 literal 字符串数组转换为HashSet,这样就不必定义中间变量SomethingList

var directions = new HashSet<string>(new [] {"east", "west", "north", "south"});

答案 6 :(得分:0)

enter image description here

List<int> a1 = new List<int> { 1, 2 };
List<int> b1 = new List<int> { 2, 3 };
List<int> a2 = new List<int> { 1, 2, 3 };
List<int> b2 = new List<int> { 1, 2, 3 };
List<int> a3 = new List<int> { 2, 3 };
List<int> b3 = new List<int> { 1, 2, 3 };

List<int> a4 = new List<int> { 1, 2, 3 };
List<int> b4 = new List<int> { 2, 3 };
List<int> a5 = new List<int> { 1, 2 };
List<int> b5 = new List<int> { };
List<int> a6 = new List<int> { };
List<int> b6 = new List<int> { 1, 2 };
List<int> a7 = new List<int> { };
List<int> b7 = new List<int> { };

HashSet<int> first = new HashSet<int>(a1);
HashSet<int> second = new HashSet<int>(b1);
first.Overlaps(second);

first = new HashSet<int>(a2);
second = new HashSet<int>(b2);
first.Overlaps(second);

first = new HashSet<int>(a3);
second = new HashSet<int>(b3);
first.Overlaps(second);

first = new HashSet<int>(a4);
second = new HashSet<int>(b4);
first.Overlaps(second);

first = new HashSet<int>(a5);
second = new HashSet<int>(b5);
first.Overlaps(second);

first = new HashSet<int>(a6);
second = new HashSet<int>(b6);
first.Overlaps(second);

first = new HashSet<int>(a7);
second = new HashSet<int>(b7);
first.SetEquals(second);