1

Following roughly this answer, I want to get the first cookie with a certain name given an URI.

Uri uri = new Uri(url);
CookieContainer cookieJar = new CookieContainer();
...
CookieCollection cookies = cookieJar.GetCookies(uri);

Then, I can access the first (and at the moment the only) cookie like this.

Cookie cookie = cookies[0];

I see it's a collection and it has an enumerator. However, when I try to use LINQ, it seems that the collection isn't getting anything like this.

Cookie cookie = cookies
  .First(c => c.Name == "vanilla");

The LINQ is imported at the top and it definitely works with a few test lines I threw in. There's no AsList() or ToArray() according to the intellisense, neither. The collection seems not to be very collection'ish.

What am I missing?

edit

I ended up copying over the contents like this. But it seems to clunky...

Cookie[] cookies = new Cookie[cookieJar.Count];
cookieJar.GetCookies(uri).CopyTo(cookies, 0);
Cookie cookie = cookies
  .First(c => c.Name == "pm_retention_urls");
Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438

1 Answers1

7

CookieCollection only implements IEnumerable and not IEnumerable<Cookie>. You can create an IEnumerable<Cookie> using Cast:

Cookie cookie = cookies.Cast<Cookie>().First(c => c.Name == "vanilla");
Lee
  • 142,018
  • 20
  • 234
  • 287
  • Are you saying that `IEnumerable` isn't LINQ'able and that it's generic counterpart `IEnumerable` is? I haven't noticed that ever (doing LINQ since 2007 I somehow failed to use it on untyped version). – Konrad Viltersten Sep 23 '19 at 12:13
  • @KonradViltersten - Yes, almost all LINQ methods are on `IEnumerable` not `IEnumerable`, the only `IEnumerable` methods are `Cast` and `OfType` which are used to create generic sequences from non-generic ones. – Lee Sep 23 '19 at 12:17
  • Well, what do you know? 12 years later and I still learn new, basic stuff. Not sure if amazed or embarrassed... :) – Konrad Viltersten Sep 23 '19 at 12:30