blog community

Welcome to blog community Sign in | Join | Help
in Search

Raimond Brookman

Architecture and .NET Development

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: ,
Published Monday, April 07, 2008 6:43 PM by Raimondb
Filed under: , ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

 

frankb said:

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.

April 7, 2008 7:47 PM
 

Wouter said:

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

April 7, 2008 9:32 PM
 

willemm said:

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);

   }

}

April 13, 2008 4:23 PM

Leave a Comment

(required) 
(optional)
(required) 
Submit

This Blog

Syndication

News

Subscribe in NewsGator Online

Subscribe in Bloglines

Add to Google


 Visitors since June 2005




Powered by Community Server, by Telligent Systems