I'm just starting to learn c# by creating my own program that is basically a damage calculator for the game Risk of Rain 2. As such, right now I am trying to create the user selection for a ability that a survivor has. I am currently using this format for how I store the ability and it's information:
Dictionary<string, Dictionary<string, double[]>> survivorAbilities =
new Dictionary<string, Dictionary<string, double[]>>();
Dictionary<string, double[]> acridAbilities =
new Dictionary<string, double[]>();
An example of some of the data being stored is:
//Epidemic: Special 1
double[] acridEpidemic = new double[3];
acridEpidemic[0] = (1); //instances
acridEpidemic[1] = (1); //damage %
acridEpidemic[2] = (1); //proc
acridAbilities.Add("epidemic", acridEpidemic);
//Initializing Acrid and his abilities
survivorAbilities.Add("acrid", acridAbilities);
The problem is that the survivor "Acrid" is only one of the four survivors that I decided to add. The other survivors have different dictionary names specific to the survivor. For example, instead of "acridAbilities", there is "commandoAbilities". I want to print each key in these dictionaries, but I'm not sure how to specify which survivor's dictionary to pick from, from the dictionary "survivorAbilities". Sorry if its a bit confusing and long, not quite sure what to put.
CodePudding user response:
This is not a direct answer to your question, but some advice since you're learning C# as well as an alternate approach.
A dictionary of nested dictionaries is, of course, perfectly valid code, but it can be confusing. Instead, why not create some classes to easily encapsulate your data? For example, you have this in your sample code:
acridEpidemic[0] = (1); //instances
acridEpidemic[1] = (1); //damage %
acridEpidemic[2] = (1); //proc
Notice you're using comments to explain what these keys in the dictionary are supposed to represent? This is not good; the code should be able to explain what it's doing without needing comments like these.
Here is an example, based on my understanding of your problem, of what I'd consider a better approach:
public void SomeExample()
{
var survivors = new List<Survivor>(); // all your survivors go in here
var acrid = new Survivor
{
Name = "Acrid",
};
acrid.Abilities.Add(new Ability
{
Name = "epidemic",
Instances = 1,
Damage = 1,
Proc = 1,
});
survivors.Add(acrid);
}
public class Survivor
{
public string Name { get; set; }
public List<Ability> Abilities { get; set; } = new List<Ability>();
}
public class Ability
{
public string Name { get; set; }
public double Instances { get; set; }
public double Damage { get; set; }
public double Proc { get; set; }
}
CodePudding user response:
You can iterate over keys of outer dictionary to print each key from inner dictionary.
foreach(var kvp in survivorAbilities)
{
foreach(var innerKVP in survivorAbilities[kvp.Key])
Console.WriteLine(innerKVP.Key); //This will print "epidemic", ..
}