Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an array to a HashSet<T> in .NET

Tags:

c#

.net

How do I convert an array to a hash set ?

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

I need to convert this list to a hashset.

like image 524
devforall Avatar asked Nov 11 '10 16:11

devforall


3 Answers

You do not specify what type BlockedList is, so I will assume it is something that derives from IList (if meant to say String where you wrote BlockList then it would be a string array which derives from IList).

HashSet has a constructor that takes an IEnumerable, so you need merely pass the list into this constructor, as IList derives from IEnumerable.

var set = new HashSet(BlockedList);
like image 186
Paul Ruane Avatar answered Nov 20 '22 14:11

Paul Ruane


I'm assuming BlockList is a string (hence the call to Split) which returns a string array.

Just pass the array (which implements IEnumerable) to the constructor of the HashSet:

var hashSet = new HashSet<string>(BlockedList);
like image 21
Justin Niessner Avatar answered Nov 20 '22 14:11

Justin Niessner


Here is an extension method that will generate a HashSet from any IEnumerable:

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

To use it with your example above:

var hashSet = BlockedList.ToHashSet();
like image 12
Jake Pearson Avatar answered Nov 20 '22 12:11

Jake Pearson