Using a combination of two fields as a key in a dictionary

I need to save a C # dict where I can store elements based on IntPtr and enumeration (when using canable to int, if that helps). In other words, if I get the same match between IntPtr and enum (named sp_playlist_type), I need to get the same result, but only then (this is also important). I decided that I would create a structure containing two and override GetHashCode (), but then I need a hashing algorithm that does not duplicate two numbers, and generates the same result every time the same number is present.

+3
source share
4 answers

I think that based on the way you create Tuple GetHashCode and Equality, you can:

Dictionary<Tuple<IntPtr, YourEnum>, YourResultType>

, .NET 4.0, .

+6

,

. GetHashCode(), . -, .

. XOR - - .

+7

- , . :

private string GetKey(IntPrt prt, sp_playlist_type playlist_type)
{
    return string.format("{0}#{1}", prt, type)
}

, - :

mydic.add(GetKey(ptr, playlist_type), myvalue);
+1

GetHashCode, , , , .

Equals , MSDN.

In this case, it is recommended to override GetHashCode . Probably, in this case XOR IntPtr and enumeration (LS 32-bit IntPtr in a 64-bit system).

0
source

Source: https://habr.com/ru/post/1791017/


All Articles