在.NET中将一个数组转换为HashSet<T>

72

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

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

我需要将这个列表转换为一个hashset


这是什么类型的列表/数组?它包含什么? - Bernard
称其为“BlockList”非常误导人,我建议使用“BlockNames”。 - Hans Passant
1
可能是重复的问题:如何将Linq结果转换为HashSet或HashedSet - nawfal
7个回答

116
您没有指定 BlockedList 的类型,因此我假设它是从 IList 继承而来的(如果您在写 BlockList 时想表达的是 String,那么这将是一个字符串数组,继承自 IList)。 HashSet 有一个接受 IEnumerable 参数的构造函数,所以您只需要将列表传递给该构造函数即可,因为 IList 继承自 IEnumerable
var set = new HashSet(BlockedList);

3
调用一个带有字符数组和StringSplitOptions参数的Split方法,对这个神秘类型进行操作,暗示着BlockedList是一个字符串。 - Jamiec
尽管我不喜欢做出假设,但从.Split方法和StringSplitOptions来看,我不得不假设是String数组。 - IAbstract

21
我假设BlockList是一个字符串(因此调用Split),它返回一个字符串数组。
只需将该数组(实现IEnumerable)传递给HashSet的构造函数即可:
var hashSet = new HashSet<string>(BlockedList);

14

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

现在有一个内置的ToHashSet方法:

var hashSet = BlockedList.ToHashSet();

12

这里有一个扩展方法,可以从任何IEnumerable生成一个HashSet:

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

要使用它以您上面的示例为例:

var hashSet = BlockedList.ToHashSet();

2

扩展示例中缺少了新的关键字...

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

1
为了更进一步,下面的一行代码演示了如何将一个字面量字符串数组转换为 HashSet,这样您就不必定义一个中间变量 SomethingList。请保留html标签。
var directions = new HashSet<string>(new [] {"east", "west", "north", "south"});

1
虽然它没有回答原始问题,但是它帮助了我! - Jay Bose

-2

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);

1
他说的是数组,不是列表。 - Jaacko Torus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接