我如何Cookies集合转换成一个通用的列表?容易 [英] How do I convert the Cookies collection to a generic list? Easily
问题描述
任何人都知道我可以转换 Request.Cookies时
到名单,其中,的HttpCookie>
?以下没有工作,因为它会抛出异常。
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>());
异常:无法转换类型'System.String'的对象键入System.Web.HttpCookie的
推荐答案
出现这种情况的原因是因为<一href="http://msdn.microsoft.com/en-us/library/system.collections.specialized.nameobjectcollectionbase.aspx"><$c$c>NameObjectCollectionBase$c$c>键入 Request.Cookies时
从枚举派生了集合的钥匙,而不是所有的值。所以,当你列举在 Request.Cookies时
收集你所得到的钥匙:
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:
由于在评论部分,并在<一指出@乔恩贝内迪克托href="http://stackoverflow.com/questions/2922762/how-do-i-convert-the-cookies-collection-to-a-generic-list-easily/2922953#2922953">his回答使用 AllKeys
属性是更理想的,因为它节省了转换:
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();
这篇关于我如何Cookies集合转换成一个通用的列表?容易的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!