While fluent is nice, I'd be more interested in adding an AddRange
(or two):
public static void AddRange<T>(this ICollection<T> collection,
params T[] items)
{
if(collection == null) throw new ArgumentNullException("collection");
if(items == null) throw new ArgumentNullException("items");
for(int i = 0 ; i < items.Length; i++) {
collection.Add(items[i]);
}
}
public static void AddRange<T>(this ICollection<T> collection,
IEnumerable<T> items)
{
if (collection == null) throw new ArgumentNullException("collection");
if (items == null) throw new ArgumentNullException("items");
foreach(T item in items) {
collection.Add(item);
}
}
The params T[]
approach allows AddRange(1,2,3,4,5)
etc, and the IEnumerable<T>
allows use with things like LINQ queries.
If you want to use a fluent API, you can also write Append
as an extension method in C# 3.0 that preserves the original list type, by appropriate use of generic constraints:
public static TList Append<TList, TValue>(
this TList list, TValue item) where TList : ICollection<TValue>
{
if(list == null) throw new ArgumentNullException("list");
list.Add(item);
return list;
}
...
List<int> list = new List<int>().Append(1).Append(2).Append(3);
(note it returns List<int>
)