Skip to content

Commit e6816e3

Browse files
committed
Introduced new ToHashSet extension methods
The two extension methods allow for method chaining, which may make code more readable - opposed to having to call the HashSet<T> constructor manually.
1 parent a8fdbd2 commit e6816e3

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

src/Skybrud.Essentials/Collections/Extensions/EnumerableExtensions.cs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,31 @@ public static Array ToArray(this IEnumerable source, Type targetType) {
113113
.Invoke(null, new object[] { source });
114114
}
115115

116+
/// <summary>
117+
/// Creates a <see cref="HashSet{TResult}"/> from an <see cref="IEnumerable{T}"/> according to specified selector function.
118+
/// </summary>
119+
/// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam>
120+
/// <typeparam name="TResult">The type of the value returned by <paramref name="selector"/>.</typeparam>
121+
/// <param name="source">An <see cref="IEnumerable{T}"/> to create a <see cref="HashSet{TResult}"/> from.</param>
122+
/// <param name="selector">A function to extract a key from each element.</param>
123+
/// <returns>A <see cref="HashSet{TResult}"/> that contains values of type <typeparamref name="TResult"/> selected from the input sequence.</returns>
124+
public static HashSet<TResult> ToHashSet<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector) {
125+
return new HashSet<TResult>(source.Select(selector));
126+
}
127+
128+
/// <summary>
129+
/// Creates a <see cref="HashSet{TResult}"/> from an <see cref="IEnumerable{T}"/> according to specified selector function.
130+
/// </summary>
131+
/// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam>
132+
/// <typeparam name="TResult">The type of the value returned by <paramref name="selector"/>.</typeparam>
133+
/// <param name="source">An <see cref="IEnumerable{T}"/> to create a <see cref="HashSet{TResult}"/> from.</param>
134+
/// <param name="selector">A function to extract a key from each element.</param>
135+
/// <param name="comparer">The <see cref="IEqualityComparer{T}"/> implementation to use when comparing values in the set, or null to use the default <see cref="EqualityComparer{T}"/> implementation for the set type.</param>
136+
/// <returns>A <see cref="HashSet{TResult}"/> that contains values of type <typeparamref name="TResult"/> selected from the input sequence.</returns>
137+
public static HashSet<TResult> ToHashSet<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector, IEqualityComparer<TResult> comparer) {
138+
return new HashSet<TResult>(source.Select(selector), comparer);
139+
}
140+
116141
}
117142

118143
}

0 commit comments

Comments
 (0)