Adding sets of items to arbitrary collections using extensions methods
Don't you just hate the fact that only some collection classes provide a possibility too add more than one item at once (such as List<T> does offer via AddRange).
This means that often I'm writing this kind of code:
var q = <some cool linq query>;
foreach(var i in q)
{
someCollection.Add(i);
}
So I decided to write a little extension method to solve this problem; see below:
public static class CollectionExtension
{
public static void AddRange<T>(this ICollection<T> target, IEnumerable<T> source)
{
foreach (T item in source)
{
target.Add(item);
}
}
}
This allows you to write code like:
var q = <some cool linq query>;
someCollection.AddRange(q);
Seems like just a bit of saving, but when you apply this throughout the code, you will find it to save quite a bit. And I think it makes the code more readable…
Not the most advanced extension method ever 🙂 , but hey, if it helps…