Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There's already an extension method which will do this. Just stick this at the end of your existing query:</p> <pre><code>.ToDictionary(x =&gt; x.FileHash, x =&gt; x.Files); </code></pre> <p>However: using <code>Encoding.UTF8.GetString</code> to convert <em>arbitrary binary data</em> into a string is a really bad idea. Use <code>Convert.ToBase64String</code> instead. The hash is <em>not</em> a UTF-8 encoded string, so don't treat it as one.</p> <p>You're also grouping by hash twice, which I suspect isn't really what you want to do.</p> <p>Alternatively, remove the previous <code>GroupBy</code> calls and use a <code>Lookup</code> instead:</p> <pre><code>var query = Directory.GetFiles(searchFolder, "*.*") .Select(f =&gt; new { FileName = f, FileHash = Convert.ToBase64String( new SHA1Managed().ComputeHash(...)) }) .ToLookup(x =&gt; x.FileHash, x =&gt; x.FileName); </code></pre> <p>That will give you a <code>Lookup&lt;string, string&gt;</code>, which is basically the files grouped by hash.</p> <p>One further thing to note: I suspect you'll be leaving file streams open with this method. I suggest you write a small separate method to compute the hash of a file based on its name, but making sure you close the stream (with a <code>using</code> statement in the normal way). This will also end up making your query simpler - something along the lines of:</p> <pre><code>var query = Directory.GetFiles(searchFolder) .ToLookup(x =&gt; ComputeHash(x)); </code></pre> <p>It's hard to simplify it much further than that :)</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