Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><code>Dictionary.ContainsKey(employee)</code> won't help here because the employee is the "unknown" value, and <code>Contains</code> won't help because it takes a <code>KeyValuePair&lt;employee,manager&gt;</code> and ... once again ... no employee is known. <code>ContainsValue(manager)</code> won't help because it doesn't return any key <em>and</em> because it's not a key, it is an <code>O(n)</code> operation, not an <code>O(1)</code> like <code>ContainsKey</code>!</p> <p>With the <em>current</em> structure the only way is with some form of looping, although I would write it like this:</p> <pre><code>// Key is Employee, Value is Manager // This is O(n) var theEmployees = relations .Where(rel =&gt; rel.Value.Equals(theManager)) .Select(rel =&gt; rel.Key); </code></pre> <p>This will only work after <code>manager</code> is given a valid <code>Equals</code> implementation. Note that the hash code <em>is not used at all</em>. (<strong>Because objects that are <em>different</em> may share the <em>same</em> hash-code, just comparing the hash-code is not a replacement for <code>Equals</code>, or <code>==</code>, or <code>CompareTo</code>!</strong> -- depending on which one is appropriate.)</p> <p>If there will be <em>many</em> such queries then the initial structure can be "inverted".</p> <pre><code>// Build a reverse lookup-up var employeesForManager = relations .GroupBy(rel =&gt; rel.Value) // group on Manager .ToDictionary(g =&gt; g.Key, g =&gt; g); // Key is the group's Manager // This is O(1), but only valid AFTER employeesForManager is [re-]generated var theEmployees = employeesForManager[theManager] </code></pre> <p>This will only work if <code>manager</code> has a valid <code>Equals</code> and <code>GetHashCode</code> implementation. (GetHashCode is required because <code>manager</code> objects are used the key to the new Dictionary.)</p> <p>As for which is "better" -- well, that depends. It is silly to create the reverse-lookup to only use it once, for instance. There is no performance problem until there is a performance problem: write clean code and profile.</p> <p>Happy coding.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

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