views:

194

answers:

5

Let's say I have List<Cookie> and I want to convert it to a CookieCollection. What's the easiest way to do this?

I know I can use a foreach loop, but isn't there a way to instantiate it with code similar to this?

List<Cookie> l = ...;
var c = new CookieCollection() { l };

When I try to compile that though, I get the error:

The best overloaded Add method 'System.Net.CookieCollection.Add(System.Net.CookieCollection)' for the collection initializer has some invalid arguments

btw, there are two Add methods that CookieCollection supports:

public void Add(Cookie cookie);
public void Add(CookieCollection cookies);
+1  A: 

You can pass a lambda to the ForEach method of a List. This will work independent of the constructors of the CookieCollection.

List<Cookie> l = ...;
var c = new CookieCollection();
l.ForEach(tempCookie => c.Add(tempCookie));
Jake Pearson
+4  A: 

CookieCollection was written before .Net 2 (before Generics). Therefore, there's really no quick nice way to do it other than manually with a foreach loop.

BFree
Thanks for the explanation as to why there is no quick way to do it.
Senseful
You don't have to manually use a C# foreach loop if you use the List<T>.ForEach(..) method Paul Creasey posted in his answer.
John K
@jdk: That's still a foreach loop just with different syntax.
BFree
A: 
List<Cookie> l = ...;
var c = new CookieCollection();
l.ForEach(x => c.Add(x));
Paul Creasey
C# 3.x and using System.Collections.Generic;
John K
A: 

You might consider looking at this (potentially) duplicate question.

Ed Altorfer
This isn't a Collection<T> though, it implements ICollection.
Senseful
The answer in that question actually covers if it's Collection<T> or ICollection, and it's the same response you marked as the answer here.
Ed Altorfer
+7  A: 

Given c and l as in your first example, this'll do:

l.ForEach(c.Add);
David Hedlund
didn't realise you could skip the lambda, nice.
Paul Creasey
well yes `x => y(x)` is just shorthand for "a function that takes x, and does y with it", and since `c.Add` meets that description as well, you can pass that function just as your rather-anonymously-typed-lambda =) 'tis neat
David Hedlund
Interesting shortcut. Too bad you can't mark two answers as accepted. In this case though, I was a bit more interested as to why I couldn't initialize it with that form, so I accepted the other answer.
Senseful