Convert List<Cookie> to CookieCollection in C#
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 开发者_StackOverflowknow 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);
Given c
and l
as in your first example, this'll do:
l.ForEach(c.Add);
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.
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));
List<Cookie> l = ...;
var c = new CookieCollection();
l.ForEach(x => c.Add(x));
精彩评论