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 ToList(
this IEnumerable source,
int capacity)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
var list = new List(capacity);
list.AddRange(source);
return list;
}
public static Dictionary ToDictionary(
this IEnumerable source,
Func keySelector,
int capacity,
IEqualityComparer comparer = null)
{
return source.ToDictionary(
keySelector, x => x, capacity, comparer);
}
public static Dictionary ToDictionary(
this IEnumerable source,
Func keySelector,
Func elementSelector,
int capacity,
IEqualityComparer 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(capacity, comparer);
foreach (TSource local in source)
{
dictionary.Add(keySelector(local), elementSelector(local));
}
return dictionary;
}