如何将数组转换为哈希集?
string[] BlockedList = BlockList.Split(new char[] { ';' },
StringSplitOptions.RemoveEmptyEntries);
我需要将这个列表转换为一个hashset
。
如何将数组转换为哈希集?
string[] BlockedList = BlockList.Split(new char[] { ';' },
StringSplitOptions.RemoveEmptyEntries);
我需要将这个列表转换为一个hashset
。
BlockedList
的类型,因此我假设它是从 IList
继承而来的(如果您在写 BlockList
时想表达的是 String
,那么这将是一个字符串数组,继承自 IList
)。
HashSet
有一个接受 IEnumerable
参数的构造函数,所以您只需要将列表传递给该构造函数即可,因为 IList
继承自 IEnumerable
。var set = new HashSet(BlockedList);
StringSplitOptions
参数的Split
方法,对这个神秘类型进行操作,暗示着BlockedList
是一个字符串。 - Jamiec.Split
方法和StringSplitOptions
来看,我不得不假设是String
数组。 - IAbstractvar hashSet = new HashSet<string>(BlockedList);
现在有一个内置的ToHashSet
方法:
var hashSet = BlockedList.ToHashSet();
这里有一个扩展方法,可以从任何IEnumerable生成一个HashSet:
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
{
return new HashSet<T>(source);
}
要使用它以您上面的示例为例:
var hashSet = BlockedList.ToHashSet();
扩展示例中缺少了新的关键字...
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
{
return new HashSet<T>(source);
}
SomethingList
。请保留html标签。var directions = new HashSet<string>(new [] {"east", "west", "north", "south"});
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);