
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…
3 comments
Somehow Microsoft has ‘forgotten’ a whole lot of usefull Extentsion methods in the framework. I would expect to find methods like this one in the next Framework version. Until then I will all your addition to my personal utility set.
frankb
You are now my extension method god!! 🙂
btw, List already has an AddRange method… So the canonical sample in the first paragraph is slightly off.
Wouter
Wouter
I agree with Frank, there’s loads more goodness to be added to linq. One of the things I like to see is the Each extension.
public static void Each(this IEnumerable sequence,Action action)
{
foreach(T item in sequence)
{
action(T);
}
}
willemm