I have some objects in List, let\'s say List and MyClass has several properties. I would like to create an index of the list based on 3 properti
Now that VS2017/C#7 has come out, the best answer is to use ValueTuple:
// declare:
Dictionary<(string, string, int), MyClass> index;
// populate:
foreach (var m in myClassList) {
index[(m.Name, m.Path, m.JobId)] = m;
}
// retrieve:
var aMyClass = index[("foo", "bar", 15)];
I chose to declare the dictionary with an anonymous ValueTuple (string, string, int). But I could have given them names (string name, string path, int id).
Perfwise, the new ValueTuple is faster than Tuple at GetHashCode but slower at Equals. I think you'd need to do complete end-to-end experiments to figure out which is really fastest for your scenario. But the end-to-end niceness and language syntax for ValueTuple makes it win out.
// Perf from https://gist.github.com/ljw1004/61bc96700d0b03c17cf83dbb51437a69
//
// Tuple ValueTuple KeyValuePair
// Allocation: 160 100 110
// Argument: 75 80 80
// Return: 75 210 210
// Load: 160 170 320
// GetHashCode: 820 420 2700
// Equals: 280 470 6800