blog community
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...

Tags van Technorati: ,

Posted 07-04-2008 18:43 by Raimondb
Filed under: , ,

Comments

frankb wrote re: Adding sets of items to arbitrary collections using extensions methods
on 07-04-2008 19:47

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.

Wouter wrote re: Adding sets of items to arbitrary collections using extensions methods
on 07-04-2008 21:32

You are now my extension method god!! :)

btw, List<T> already has an AddRange method... So the canonical sample in the first paragraph is slightly off.

Wouter

willemm wrote re: Adding sets of items to arbitrary collections using extensions methods
on 13-04-2008 16:23

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<T>(this IEnumerable<T> sequence,Action<T> action)

{

   foreach(T item in sequence)

   {

       action(T);

   }

}

Add a Comment

(required)  
(optional)
(required)  
Remember Me?
Enter code (required)
Powered by Community Server (Commercial Edition), by Telligent Systems