M
M
maxcad2021-08-20 12:24:42
C++ / C#
maxcad, 2021-08-20 12:24:42

C#. Searching for byte keys in a dictionary. What am I doing wrong?

Here is an example.

byte[] bufer1 = new byte[5] { (byte)4, (byte)0, (byte)91, (byte)204, (byte)2 };
byte[] bufer2 = new byte[5] { (byte)4, (byte)0, (byte)91, (byte)204, (byte)2 };

Dictionary<byte[], string> Dict = new Dictionary<byte[], string>();

Dict.Add(bufer2, "bla bla bla");

bool test = Dict.ContainsKey(bufer1);

Console.WriteLine(Dict[bufer1]);
Console.ReadLine();


I understand that if the arrays have the same content, then this does not mean that they are equal. And the key in the dictionary is a reference to the buffer2 variable.
Therefore, the test variable is not true, but Console.WriteLine(Dict[bufer1]); throws an exception.

As I understand it, I will not be able to pull out a value from the dictionary by key if the key is not a reference to a variable, even though they have the same content?

I wanted to create a data storage structure in which you can pull out string values ​​by the byte key Dict[byte[]]. But it doesn't work if the key is a byte array.
Or can something be done?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Ilya, 2021-08-20
@maxcad

implement IEqualityComparer<byte[]>and pass to the dictionary when it is created

V
Vasily Bannikov, 2021-08-20
@vabka

Here are a couple of options:
1. Convert the array to a base64 string and use it as a key
2. If the size is fixed at 5 - you can use (byte, byte, byte, byte ,byte) (a tuple of five bytes)
3. Since the size is only 5 bytes , then you can make a wrapper structure (in which there will be 5 byte fields)
4. You can store bytes in int64
5. You can read the hash from the byte array and use the hash as a key.
6. In principle, you can make a wrapper over an array with custom Equals and GetHashCode.

M
maxcad, 2021-08-20
@maxcad

But on the other hand, this method of data storage has another positive point.
For example, you can store several identical keys in a dictionary. This means that one set of data can be assigned several different values.

byte[] bufer1 = new byte[5] { (byte)4, (byte)0, (byte)91, (byte)204, (byte)2 };
byte[] bufer2 = new byte[5] { (byte)4, (byte)0, (byte)91, (byte)204, (byte)2 };
Dictionary<byte[], string> Dict = new Dictionary<byte[], string>();
Dict.Add(bufer1, "bla bla bla");
Dict.Add(bufer2, "tra la la");

True, extraction and selection will have to be done by a complete enumeration of the dictionary and a comparison of the contents of the keys, which is a little energy-consuming.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question