Answer the question
In order to leave comments, you need to log in
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();
Answer the question
In order to leave comments, you need to log in
implement IEqualityComparer<byte[]>
and pass to the dictionary when it is created
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.
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");
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question