Is there a way to directly access the source key object from the C # dictionary (where the key is a reference type)? I saw this question on another site ( http://www.pcreview.co.uk/forums/get-original-key-object-dictionary-t3351718.html ), and since most respondents did not understand why this is a reasonable question / not As a symptom of poor basic design, I will go into detail below.
The workarounds that I still have are:
(a) iterate over keys that verify equality, which is the complexity of O (n): (
(b) maintain an additional pool (for example, another dictionary that displays keys for itself). This leads to O (1) complexity, but requires additional memory, additional work, when elements are added to the dictionary, risking not getting the right coordination ... none of this is fatal, but it is not ideal and will not be needed if the Dictionary < > suggested a method for extracting a key with a key.
In particular, I have a dictionary <State, List <State →, which is a state graph: each key represents a state of a finite state machine, and the value associated with it is a list of neighboring states that can be reached from there. for example, a state can represent a chessboard configuration, and neighboring states are configurations achievable in one move.
, , , . , ( ). - (.. ) GetHashCode Equals.
. - , , , N M , NxM , N State NxM . , , - Equals().
, , , :
public class StateGraphExample
{
public static void Main()
{
State initialState = State.GetInitialState();
var graph = new Dictionary<State, List<State>>();
BuildGraph(initialState, graph);
}
public static void BuildGraph(State state, Dictionary<State, List<State>> graph)
{
var neighbours = new List<State>();
foreach (State.Move move in state.GetValidMoves())
neighbours.Add(state.ApplyMove(move));
graph[state] = neighbours;
foreach (State neighbour in neighbours)
if (!graph.ContainsKey(neighbour))
BuildGraph(neighbour, graph);
}
public class State
{
public static State GetInitialState()
{ }
public class Move
{ }
public List<State.Move> GetValidMoves()
{ }
public State ApplyMove(State.Move move)
{ }
public override int GetHashCode()
{ }
public override bool Equals(object obj)
{ }
private State Clone()
{ }
}
}