Note that there are some explanatory texts on larger screens.

plurals
  1. POChallenge: elegantly LINQify this procedural code
    text
    copied!<pre><code>string[] filesOfType1 = GetFileList1(); string[] filesOfType2 = GetFileList2(); var cookieMap = new Dictionary&lt;string, CookieContainer&gt;(); Action&lt;string, Func&lt;string, KeyValuePair&lt;string, CookieContainer&gt;&gt;&gt; addToMap = (filename, pairGetter) =&gt; { KeyValuePair&lt;string, CookieContainer&gt; cookiePair; try { cookiePair = pairGetter(filename); } catch { Console.WriteLine("An error was encountered while trying to read " + file + "."); return; } if (cookieMap.ContainsKey(cookiePair.Key)) { if (cookiePair.Value.Count &gt; cookieMap[cookiePair.Key].Count) { cookieMap[cookiePair.Key] = cookiePair.Value; } } else { cookieMap.Add(cookiePair.Key, cookiePair.Value); } }; foreach (string file in filesOfType1) { addToMap(file, GetType1FileCookiePair); } foreach (string file in filesOfType2) { addToMap(file, GetType2FileCookiePair); } </code></pre> <p>Salient features that must be preserved:</p> <ul> <li>Files of type 1 are more important than files of type 2; i.e. if a file of type 1 maps to a (key, value1) combination and a file of type 2 maps to a (key, value2) combination, then we add (key, value1) to cookieMap and <em>not</em> (key, value2). <strong>Edit: as pointed out by Bevan, this is not satisfied by my original procedural code.</strong></li> <li>Secondarily, <code>CookieContainer</code>s with a higher <code>Count</code> have higher priority, i.e. if there are two (key, value) combos for the same key and both from the same filetype, we choose the one with higher <code>value.Count</code>.</li> <li>Per-case exception handling is a must; screwing up a single file-reading should just allows us to note that and continue.</li> </ul> <p>My best attempt started like this:</p> <pre><code>var cookieMap = (filesOfType1.Select(file =&gt; GetType1FileCookiePair(file)) .Concat(filesOfType2.Select(file =&gt; GetType2FileCookiePair(file)))) .GroupBy(pair =&gt; pair.Key) .Select(/* some way of selecting per the above bullets */) .ToDictionary(pair =&gt; pair.Key, pair =&gt; pair.Value); </code></pre> <p>But it's inelegant and filling in that comment block seems like a bitch. Right now I'm happy to stay procedural, but I thought that it might be a fun challenge to see if people can come up with something really clever.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload