S
S
sstas2022-02-15 19:52:25
C++ / C#
sstas, 2022-02-15 19:52:25

How to get values ​​by new key instance in dictionary?

Hello. There is a list of objects that need to be stored in an array with the ability to find them by coordinates, I decided to write them to a dictionary and set a class with two-dimensional coordinates as a key, but when I try to get a value from a new key instance, an error pops up that the value was not found. How can the problem be solved? Save more links?

public class CellPos
{ 
    public int x;
    public int y;
}

...
public static Dictionary<CellPos, Cell> CellArray = new Dictionary<CellPos, Cell>();
...
CellArray.ContainsKey(new CellPos(1, 1));//false

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
freeExec, 2022-02-15
@freeExec

Read how the Dictionary works and why you need GetHashCode()and Equals().
So far, you can only find the same instance, not "by coordinates".

V
Vasily Bannikov, 2022-02-15
@vabka

The simplest option is to declare CellPos as a record:

public record struct CellPos(int X, int Y); //record struct, тк объект маленький и очень похож на value-object

Then it can be used as a key in a dictionary.
A slightly more complicated option, or if you are using an old version of the language and runtime (I strongly advise you to upgrade, if possible):
Add the GetHashCode and Equals methods yourself.
Read about how they should work here: https://docs.microsoft.com/en-us/dotnet/api/system...
Option three, if you can't touch CellPos in any way - create a new class that will implement interface System.Collections.Generic.IEqualityComparer<CellPos> and pass it to the dictionary (there is a parameter there)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question