ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

ToHashSet<T>

Takes any IEnumerable<T> and converts it to a HashSet<T>

Source

/// <summary>
		/// Converts an IEnumerable to a HashSet
		/// </summary>
		/// <typeparam name="T">The IEnumerable type</typeparam>
		/// <param name="enumerable">The IEnumerable</param>
		/// <returns>A new HashSet</returns>
		public static HashSet<T> ToHashSet<T>(this IEnumerable<T> enumerable) {
	HashSet<T> hs = new HashSet<T>();
	foreach (T item in enumerable)
		hs.Add(item);
	return hs;
}

Example

List<int> li = new List<int>();
li.Add(1);
li.Add(2);
li.Add(3);

HashSet<int> hsi = li.ToHashSet<int>();

Author: FloppyMan

Submitted on: 25 aug. 2011

Language: C#

Type: System.IEnumerable<T>

Views: 11427