Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You should use tuples. They are equivalent to a CompositeKey class, but the Equals() and GetHashCode() are already implemented for you.</p> <pre><code>var myClassIndex = new Dictionary&lt;Tuple&lt;int, bool, string&gt;, MyClass&gt;(); //Populate dictionary with items from the List&lt;MyClass&gt; MyClassList foreach (var myObj in myClassList) myClassIndex.Add(Tuple.Create(myObj.MyInt, myObj.MyBool, myObj.MyString), myObj); MyClass myObj = myClassIndex[Tuple.Create(4, true, "t")]; </code></pre> <p>Or using System.Linq</p> <pre><code>var myClassIndex = myClassList.ToDictionary(myObj =&gt; Tuple.Create(myObj.MyInt, myObj.MyBool, myObj.MyString)); MyClass myObj = myClassIndex[Tuple.Create(4, true, "t")]; </code></pre> <p>Unless you need to customize the computation of the hash, it's simpler to use tuples.</p> <p>If there are a lot of properties you want to include in the composite key, the Tuple type name can become pretty long, but you can make the name shorter by creating your own class deriving from Tuple&lt;...>.</p> <hr> <p>** <strong>edited in 2017</strong> **</p> <p>There is a new option starting with C# 7: the <em>value tuples</em>. The idea is the same, but the syntax is different, lighter:</p> <p>The type <code>Tuple&lt;int, bool, string&gt;</code> becomes <code>(int, bool, string)</code>, and the value <code>Tuple.Create(4, true, "t")</code> becomes <code>(4, true, "t")</code>.</p> <p>With value tuples, it also becomes possible to name the elements. Note that performances are slightly different, so you may want to do some benchmarking if they matter for you.</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