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

dev*_*all 52 .net c#

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

string[]  BlockedList = BlockList.Split(new char[] { ';' },     
StringSplitOptions.RemoveEmptyEntries);
Run Code Online (Sandbox Code Playgroud)

我需要将此列表转换为hashset.

Pau*_*ane 92

你没有指定什么类型BlockedList,所以我认为它是从中得到的东西IList(如果意思是说String你写的地方BlockList那么它将是一个派生自的字符串数组IList).

HashSet有一个构造函数,它需要一个IEnumerable,所以你只需要将列表传递给这个构造函数,因为IList派生自IEnumerable.

var set = new HashSet(BlockedList);
Run Code Online (Sandbox Code Playgroud)

  • 在这个神秘类型上调用`Split`,使用char数组的参数和`StringSplitOptions`有点表示BlockedList是一个字符串. (3认同)

Jus*_*ner 17

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

只需将数组(实现IEnumerable)传递给HashSet构造函数:

var hashSet = new HashSet<string>(BlockedList);
Run Code Online (Sandbox Code Playgroud)


Sta*_*cev 14

2017 更新 - 适用于 .Net Framework 4.7.1+ 和 .Net Core 2.0+

现在有一个内置ToHashSet方法:

var hashSet = BlockedList.ToHashSet();
Run Code Online (Sandbox Code Playgroud)


Jak*_*son 9

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

public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
{
    return new HashSet<T>(source);
}
Run Code Online (Sandbox Code Playgroud)

要将它与上面的示例一起使用:

var hashSet = BlockedList.ToHashSet();
Run Code Online (Sandbox Code Playgroud)