You must use tuples. They are equivalent to the CompositeKey class, but Equals () and GetHashCode () are already implemented for you.
var myClassIndex = new Dictionary<Tuple<int, bool, string>, MyClass>();
Or using System.Linq
var myClassIndex = myClassList.ToDictionary(myObj => Tuple.Create(myObj.MyInt, myObj.MyBool, myObj.MyString)); MyClass myObj = myClassIndex[Tuple.Create(4, true, "t")];
If you do not need to configure hash calculation, it is easier to use tuples.
If there are many properties in the composite key that you want to include in the composite key, the Tuple type name can become quite long, but you can make it shorter by creating your own class derived from Tuple <...>.
** edited in 2017 **
There is a new parameter starting with C # 7: value tuples. The idea is the same, but the syntax is different, easier:
The type Tuple<int, bool, string> becomes (int, bool, string) , and the value Tuple.Create(4, true, "t") becomes (4, true, "t") .
With tuple values, it also becomes possible to name elements. Please note that performance is slightly different, so you might want to do a benchmarking if they are important to you.
Eldritch Conundrum Mar 14 2018-12-12T00: 00Z
source share