Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert the Cookies collection to a generic list? Easily

Anyone know how I can convert Request.Cookies into a List<HttpCookie>? The following didn't work as it throws an exception.

List<HttpCookie> lstCookies = new List<HttpCookie>(
    Request.Cookies.Cast<HttpCookie>());

Exception: Unable to cast object of type 'System.String' to type 'System.Web.HttpCookie'

like image 474
Naeem Sarfraz Avatar asked May 27 '10 16:05

Naeem Sarfraz


3 Answers

The reason this happens is because the NameObjectCollectionBase type that Request.Cookies derives from enumerates over the keys of the collection and not over the values. So when you enumerate over the Request.Cookies collection you are getting the keys:

public virtual IEnumerator GetEnumerator()
{
    return new NameObjectKeysEnumerator(this);
}

This means that the following will work:

string[] keys = Request.Cookies.Cast<string>().ToArray();

I guess you could try the following which might be considered ugly but will work:

List<HttpCookie> lstCookies = Request.Cookies.Keys.Cast<string>()
    .Select(x => Request.Cookies[x]).ToList();

UPDATE:

As pointed out by @Jon Benedicto in the comments section and in his answer using the AllKeys property is more optimal as it saves a cast:

List<HttpCookie> lstCookies = Request.Cookies.AllKeys
    .Select(x => Request.Cookies[x]).ToList();
like image 62
Darin Dimitrov Avatar answered Nov 07 '22 21:11

Darin Dimitrov


If you really want a straight List<HttpCookie> with no key->value connection, then you can use Select in LINQ to do it:

var cookies = Request.Cookies.AllKeys.Select(x => Request.Cookies[x]).ToList();
like image 36
Jon Benedicto Avatar answered Nov 07 '22 21:11

Jon Benedicto


.Cookies.Cast<HttpCookie>(); tries to cast the collection of keys to a collection of cookies. So it's normal that you get an error :)

It's a name -> value collection, so casting to a list wouldn't be good.

I would try converting it to a dictionary.

For example:

Since Cookies inherits from NameObjectCollectionBase you can GetAllKeys(), and use that list to get all the values and put them in a Dictionary.

For example:

Dictionary cookieCollection = new Dictionary<string, object>();

foreach(var key in Request.Cookies.GetAllKeys())
{
    cookieCollection.Add(key, Request.Cookies.Item[key]);
}
like image 2
Snake Avatar answered Nov 07 '22 21:11

Snake