ToList and ToDictionary with Initial Capacity
ToList and ToDictionary overloads that expose the underlying collection classes' initial capacity. Occasionally useful when source length is known or bounded.
public static List<TSource> ToList<TSource>(
this IEnumerable<TSource> source,
int capacity)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
var list = new List<TSource>(capacity);
list.AddRange(source);
return list;
}
public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
int capacity,
IEqualityComparer<TKey> comparer = null)
{
return source.ToDictionary<TSource, TKey, TSource>(
keySelector, x => x, capacity, comparer);
}
public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector,
int capacity,
IEqualityComparer<TKey> comparer = null)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (keySelector == null)
{
throw new ArgumentNullException("keySelector");
}
if (elementSelector == null)
{
throw new ArgumentNullException("elementSelector");
}
var dictionary = new Dictionary<TKey, TElement>(capacity, comparer);
foreach (TSource local in source)
{
dictionary.Add(keySelector(local), elementSelector(local));
}
return dictionary;
}