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.
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; }
}
Related
so I have 100 items that I need to store in some sort of array.
Each item has an att, def, cost, lvl, name and id(array key) value
What would be the best way to store them, keep in mind that i will need to sort the att and def values in descending order. While I have easily done this with php I am having some trouble with c#.
IF anyone could help provide a working example with just a couple of items that would be great thanks.
I am using unity and c#
Define a structure to store all the attribute:
class Enemy
{
public int Attack { get; set; }
public int Defend { get; set; }
public int Cost { get; set; }
public ....
}
Then store all in a list:
var enemies = new List<Enemy>();
...
You can sort the enemies by anything
var sortedEnemies = enemies.OrderBy(item => item.Attack).ToList();
public class Price
{
public string Symbol {get; set; }
public double AskPrice{get; set; }
public double BidPrice{get; set; }
public string Exchange{get; set; }
}
public class inputs
{
public IList<Price> Prices {get; set; }
}
var inputs = new
{
Prices = prices,
};
Price[] p = inputs.Prices.Where(x => x.Exchange == exchange).ToArray();
p.ForEach(x => x.AskPrice = 0);
For this code when I create new variable p, it is actually a reference to input.price, not a new variable. Why is this? Is there any best practice of how to deal with this behavior?
You did not make a change to p, p stayed the same, what you changed where the elements inside of p, the elements inside of p are shared between p and the original source.
To not get this behavior you need to "Deep copy" the objects when you make a new array, creating new objects for the elements with the same content as the original.
public class Price
{
public string Symbol {get; set; }
public double AskPrice{get; set; }
public double BidPrice{get; set; }
public string Exchange{get; set; }
public Price Clone()
{
var result = new Price();
result.Symbol = this.Symbol;
result.AskPrice = this.AskPrice;
result.BidPrice = this.BidPrice;
result.Exchange = this.Exchange;
return result;
}
}
public class inputs
{
public IList<Price> Prices {get; set; }
}
var inputs = new
{
Prices = prices,
};
Price[] p = inputs.Prices.Where(x => x.Exchange == exchange).Select(x=> x.Clone()).ToArray();
p.ForEach(x => x.AskPrice = 0);
Note, if you have any reference types inside of your class you need to recursively clone the entire data structure and will need to make copies of them too.
There are two different variables here - the first is the Price object(s), and the second is input.Prices, which is a List of prices.
Your LINQ code takes the inputs.Prices list, filters it and creates a new array from it, but all that does is create new collections. It doesn't change the actual objects that are in the collection. This is because classes, in C#, are all reference types, meaning that var price = input.Prices[0] just copies the reference to a single, specific instance in memory. You can copy those references between a dozen lists and arrays, but the objects are the same.
It seems that what you want is to clone or copy by value your Price objects. For that, you have two options:
Make Price a struct.
Structs, unlike classes, are value types and are copied-by-value, meaning a new copy is made whenever you assign it to a new variable. This, however, has a performance penalty, since the whole struct is copied every time it's assigned. Your struct takes up 24-32 bytes (two 64bit doubles and two 32/64 bit references to strings), which is more than the recommended rule of thumb of "no more than 16 bytes for structs", so it's probably a bad idea.
Make a Clone method.
Have your Price implement a Clone method which returns a copy of the object - or alternately, create a copy-constructor that creates a new Price with the old values. Use that in your LINQ:
public class Price
{
// your fields
public Price Clone()
{
return new Price
{
Symbol = this.Symbol,
BidPrice = this.BidPrice,
//etc.
}
}
}
var p = input.Prices.Where(x => x.Exchange == exchange).Select(x => x.Clone()).ToArray();
I'm an old, old programmer so I'm very used to abuse Arrays but I will need to start using dictionaries since they can dynamically expand and Arrays can't.
Now... I need to populate values for a solar system where each body in that solar system have perhaps about 20-30 different values.
My intention was to use a dictionary where each body has it's own unique Key and a value, such as...
Dictionary<int,string> BodyName = new Dictionary<int,string>()
Dictionary<int,int> BodySize = new Dictionary<int,int>()
Dictionary<int,int> BodyX = new Dictionary<int,int>()
Dictionary<int,int> BodyY = new Dictionary<int,int>()
Dictionary<int,int> BodyVelocity = new Dictionary<int,int>()
etc...
my question is what's the best way to go about to retrieve the values from all these dictionaries?
The key for each 'body" is the same in each dictionary. I know I can do this with lots of loops, but that seems quite wasteful on CPU cycles and that is a bad thing for me.
I also considered Dictionary,List but that has other issues I don't particularly like.
Create a composite type, and use that.
Sticking with Dictionaries is suitable if the key is a unique identifier - a planet ID? a planet name? - that must be used to look up the data. Don't forget that iteration over dictionaries is non-deterministic.
Dictionary<int,PlanetaryBody> Bodies = new Dictionary<int,PlanetaryBody>()
On the other hand, a sequence is suitable if the planets are only iterated (or accessed by positional indices). In this case, using a List often works well.
List<PlanetaryBody> Bodies = new List<PlanetaryBody>();
// Unlike arrays, Lists grows automatically! :D
Bodies.Add(new PlanetaryBody { .. });
(I very seldom choose an array over a List - it's better sometimes, but not often.)
The composite type (i.e. class) is used to group the different attributes into a larger concept or classification group:
class PlanetaryBody {
public string Name { get; set; }
public double Mass { get; set; }
// etc.
}
Just use a class for that.
public class Planet {
public int Id { get; set; }
public string Name { get; set; }
public int Size { get; set; }
// and so on for each property of whatever type you need.
}
When you need a new Planet just new up:
var planet = new Planet();
planet.Name = "Saturn";
// again finish populating the properties.
To add it to a list:
var list = new List<Planet>();
list.Add(planet);
// adding the planet you created above.
Then look into manipulating lists and so on using LINQ
I have a situation where I need a class which need to contain information about something which varies at runtime, for example:
class Info<T>
{
public T Max { get; set; }
public T Min { get; set; }
public T DefaultValue { get; set; }
public T Step { get; set; }
// Some other stuff
}
I have to store many instances of this class in a dictionary but problem is that to use dictionary I have to declare one type e.g.
Dictionary<string, Info<int>> dict = new Dictionary<string, Info<int>>();
In this case I can't add another type of info e.g. Info<double>.
I want something like , I have removed generic version in below case.
{"Price", new Info{Min=100,Max=1000,DefaultValue=200,Step=50}}
{"Adv", new Info{Min=10.50,Max=500.50,DefaultValue=20.50,Step=1.5}}
{"Answer", new Info{Min=false,Max=false,DefaultValue=false,Step=false}}
I can use Dictionary<string, Object> dict = new Dictionary<string, Object>();
but then when I get the dict item back I don't know what type is that, I need to know the type as well e.g. for Price it's int and for Adv it's double , how will I know it at runtime?
Actually I want to create a validator(I am using .Net Compact Framework 3.5/can not use any inbuilt system if it exists) for example If I have a class like below..
class Demo
{
public int Price { get; set; }
public float Adv { get; set; }
public static bool Validate(Demo d)
{
List<string> err = new List<string>();
// here I have to get Info about the Price
// from dictionary, it can be any storage
Info priceInfo = GetPriceInfo("Price");
if (d.Price < priceInfo.Min)
{
d.Price = priceInfo.Min;
err.Add("price is lower than Min Price");
}
if (d.Price > priceInfo.Max)
{
d.Price = priceInfo.Max;
err.Add("price is above than Max Price");
}
// need to do similar for all kinds of properties in the class
}
}
So idea is to store validation information at one place (in dictionary or somewhere else) and then use that info at validation time, I also would like to know if I can design the above scenario in a better way ?
Maybe there is a better way to do this , any guidelines please?
You can use a non-generic base class:
public abstract class Info {
}
public class Info<T> : Info {
}
Now all different generic types inherit from the same base type, so you can use that in the dictionary:
Dictionary<string, Info> dict = new Dictionary<string, Info>();
You can define properties and methods where the interface is not depending on the generic type in the base class, and implement them in the generic class. That way you can use them without specifying the generic type.
For methods where you need the type, you need specific code for each type. You can use the is and as operators to check for a type:
Info<int> info = dict[name] as Info<int>;
if (info != null) {
int max = info.Max;
}
You could take from Microsoft and mimic the IEnumerable interface and create a .Cast<T>? However, somebody is going to have to know about your type unless you want to get into dynamic (4.0+ only) or reflection. Both of which come with a cost. Maybe you need to rethink your design?
Keith Nicholas is right - if you want your dictionary to support multiple types, you'll need an interface, but it will need to be a generic one.
Try something like this (warning: untested code):
interface IInfo<T>
{
T Max { get; set; }
T Min { get; set; }
T DefaultValue { get; set; }
T Step { get; set; }
}
Dictionary<string, IInfo> dict = new Dictionary<string, IInfo>();
class AnswerInfo : IInfo<bool> { }
class PriceInfo : IInfo<int> { }
class AdvInfo : IInfo<double> { }
dict["Answer"] = new AnswerInfo() { Min = false, Max = false, DefaultValue = false, Step = false };
dict["Price"] = new PriceInfo() { Min = 100, Max = 1000, DefaultValue = 200, Step = 50 };
dict["Adv"] = new AdvInfo() { Min = 10.50, Max = 500.50, DefaultValue = 20.50 Step = 1.5 };
Using a Dictionary of objects (or some base class) you would have several options to get to the data (typically, involving some kind of inheritance from a common base class to work with, which has properties as outlined below).
Use an enum to denote the type, then you can have some kind of switch/case. (Easy to do, not very C#ish.)
Use something similar to a VARIANT. Variants are types that provide both information what they store and also the value stored, which can be any base type like string, int, float. (Does not really exist in C#, as you can see from the answers here Variant Type in C# .)
You can also test the type of the object at runtime to find out what kind of an object you have, and then cast it and handle its content depending on its type. (Several ways.. might have to use reflection, for a start have a look here: get object type and assign values accordingly .)
You could actually also try to abstract the operation you want to do on each object in some way, and then call that function. Something like the command pattern. (Command Pattern : How to pass parameters to a command?)
Probably many more. :)
EDIT 1: Forgot to add the nested property curve ball.
UPDATE: I have chosen #mtazva's answer as that was the preferred solution for my specific case. In retrospect, I asked a general question with a very specific example and I believe that ended up confusing everyone (or maybe just me) as to what the question was exactly. I do believe the general question has been answered as well (see the Strategy pattern answers and links). Thanks everyone!
Large switch statements obviously smell and I have seen some links on how you could do this with a dictionary that maps to functions. But I'm wondering if there is a better (or smarter way) to do this? In a way, this is a question I've always sort of had rolling around in the back of my head but never really had a good solution to.
This question stemmed from another question I asked earlier: How to select all the values of an object's property on a list of typed objects in .Net with C#
Here is an example class I'm working with (from an external source):
public class NestedGameInfoObject
{
public string NestedName { get; set; }
public int NestedIntValue { get; set; }
public decimal NestedDecimalValue { get; set; }
}
public class GameInfo
{
public int UserId { get; set; }
public int MatchesWon { get; set; }
public long BulletsFired { get; set; }
public string LastLevelVisited { get; set; }
public NestedGameInfoObject SuperCoolNestedGameInfo { get; set; }
// thousands more of these
}
Unfortunately, this is coming from an external source... imagine a HUGE data dump from Grand Theft Auto or something.
And I want to get just a small cross section of a list of these objects. Imagine we want to be able to compare you with a bunch of your friends' game info objects. An individual result for one user would look like this:
public class MyResult
{
public int UserId { get; set; } // user id from above object
public string ResultValue { get; set; } // one of the value fields from above with .ToString() executed on it
}
And an example of what I want to replace with something more manageable (believe me, I DON'T want to be maintaining this monster switch statement):
const int MATCHES_WON = 1;
const int BULLETS_FIRED = 2;
const int NESTED_INT = 3;
public static List<MyResult> GetMyResult(GameInfo[] gameInfos, int input)
{
var output = new List<MyResult>();
switch(input)
{
case MATCHES_WON:
output = gameInfos.Select(x => new MyResult()
{
UserId = x.UserId,
ResultValue = x.MatchesWon.ToString()
}).ToList<MyResult>();
break;
case BULLETS_FIRED:
output = gameInfos.Select(x => new MyResult()
{
UserId = x.UserId,
ResultValue = x.BulletsFired.ToString()
}).ToList<MyResult>();
break;
case NESTED_INT:
output = gameInfos.Select(x => new MyResult()
{
UserId = x.UserId,
ResultValue = x.SuperCoolNestedGameInfo.NestedIntValue.ToString()
}).ToList<MyResult>();
break;
// ad nauseum
}
return output;
}
So the question is are there any reasonable ways to manage this beast? What I'd really like is a dynamic way to get this info in case that initial object changes (more game info properties are added, for instance). Is there a better way to architect this so it's less clumsy?
I think your first sentence eluded to what is probably the most reasonable solution: some form of dictionary mapping values to methods.
For example, you could define a static Dictionary<int, func<GameInfo, string>>, where each value such as MATCHES_WON would be added with a corresponding lambda that extracts the appropriate value (assuming your constants, etc are defined as shown in your example):
private static Dictionary<int, Func<GameInfo, string>> valueExtractors =
new Dictionary<int, Func<GameInfo, string>>() {
{MATCHES_WON, gi => gi.MatchesWon.ToString()},
{BULLETS_FIRED, gi => gi.BulletsFired.ToString()},
//.... etc for all value extractions
};
You can then use this dictionary to extract the value in your sample method:
public static List<MyResult> GetMyResult(GameInfo[] gameInfos, int input)
{
return gameInfo.Select(gi => new MyResult()
{
UserId = gi.UserId,
ResultValue = valueExtractors[input](gi)
}).ToList<MyResult>();
}
Outside of this option, you could potentially have some sort of file/database/stored lookup with the number and the property name, then use reflection to extract the value, but that would obviously not perform as well.
I think this code is getting out of hand a bit. You're effectively using constants to index properties - and this is creating fragile code that you're looking to use some technique - such as - reflection, dictionaries, etc - to control the increased complexity.
Effectively the approach that you're using now will end up with code like this:
var results = GetMyResult(gameInfos, BULLETS_FIRED);
The alternative is to define an extension method that lets you do this:
var results = gameInfos.ToMyResults(gi => gi.BulletsFired);
This is strongly-typed, it doesn't require constants, switch statements, reflection, or anything arcane.
Just write these extension methods and you're done:
public static class GameInfoEx
{
public static IEnumerable<MyResult> ToMyResults(
this IEnumerable<GameInfo> gameInfos,
Func<GameInfo, object> selector)
{
return gameInfos.Select(gi => gi.ToMyResult(selector));
}
public static MyResult ToMyResult(
this GameInfo gameInfo,
Func<GameInfo, object> selector)
{
return new MyResult()
{
UserId = gameInfo.UserId,
ResultValue = selector(gameInfo).ToString()
};
}
}
Does that work for you?
You can use reflection for theses purposes. You can implement custom attributes, mark your properties, etc. Also, it is dynamic way to get info about your class if it changes.
If you want to manage switch code I would point you at Design Patterns book (GoF) and suggest possibly looking at patterns like Strategy and possibly Factory (thats when we talk about general case use, your case isn't very suited for Factory) and implementing them.
While switch statement still has to be left somewhere after refactoring to pattern is complete (for example, in a place where you select strategy by id), code will be much more maintanable and clear.
That said about general switch maintenance, if they become beast like, I am not sure its best solution given how similar your case statements look.
I am 100% sure you can create some method (possibly an extension method) that will be accepting desired property accessor lambda, that should be used when results are generated.
If you want your code to be more generic, I agree with the suggestion of a dictionary or some kind of lookup pattern.
You could store functions in the dictionary, but they seemly all perform the same operation - getting the value from a property. This is ripe for reflection.
I'd store all your properties in a dictionary with an enum (prefer an enum to a const) as the key, and a PropertyInfo - or, less preferred, a string which describes the name of the property - as the value. You then call the GetValue() method on the PropertyInfo object to retrieve the value from the object / class.
Here's an example where I'm mapping enum values to their 'same named' properties in a class, and then using reflection to retrieve the values out of a class.
public enum Properties
{
A,
B
}
public class Test
{
public string A { get; set; }
public int B { get; set; }
}
static void Main()
{
var test = new Test() { A = "A value", B = 100 };
var lookup = new Dictionary<Properties, System.Reflection.PropertyInfo>();
var properties = typeof(Test).GetProperties().ToList();
foreach (var property in properties)
{
Properties propertyKey;
if (Enum.TryParse(property.Name, out propertyKey))
{
lookup.Add(propertyKey, property);
}
}
Console.WriteLine("A is " + lookup[Properties.A].GetValue(test, null));
Console.WriteLine("B is " + lookup[Properties.B].GetValue(test, null));
}
You can map your const values to the names of the properties, PropertyInfo objects which relate to those properties, functions which will retrieve the property values... whatever you think suits your needs.
Of course you will need some mapping - somewhere along the way you will be depending on your input value (the const) mapping to a specific property. The method by which you can get this data might determine the best mapping structure and pattern for you.
I think the way to go is indeed some kind of mapping from one value (int) to something that is somehow a function that knows how to extract a value.
If you really want to keep it extensible, so that you can easily add some without touching the code, and possibly accessing more complex properties (ie. nested properties, do some basic computation), you may want to keep that in a separate source.
I think one way to do this is to rely on the Scripting Services, for instance evaluating a simple IronPython expression to extract a value...
For instance in a file you could store something like :
<GameStats>
<GameStat name="MatchesWon" id="1">
<Expression>
currentGameInfo.BulletsFired.ToString()
</Expression>
</GameStat>
<GameStat name="FancyStat" id="2">
<Expression>
currentGameInfo.SuperCoolNestedGameInfo.NestedIntValue.ToString()
</Expression>
</GameStat>
</GameStats>
and then, depending on the requested stat, you always end up retrieving the general GameInfos. You can them have some kind of foreach loop with :
foreach( var gameInfo in gameInfos){
var currentGameInfo = gameInfo
//evaluate the expression for this currentGameInfo
return yield resultOfEvaluation
}
See http://www.voidspace.org.uk/ironpython/dlr_hosting.shtml for examples on how to embed IronPython Scripting in a .NET application.
NOTE: when working with this kind of stuff, there are several things you must really be careful about:
this potentially allows someone to inject code in your application ...
you should measure the performance impact of Dynamic evaluation in here
I don't have a solution to your switch problem off the top of my head, but you could certainly reduce the code by using a class that can automatically map all the fields you need. Check out http://automapper.org/.
I would not have written the GetMyResult method in the first place. All it is doing is transforming GameInfo sequence into MyResult sequence. Doing it with Linq would be easier and more expressive.
Instead of calling
var myResultSequence = GetMyResult(gameInfo, MatchesWon);
I would simply call
var myResultSequence = gameInfo.Select(x => new MyResult() {
UserId = x.UserId,
ResultValue = x.MatchesWon.ToString()
});
To make it more succinct you can pass the UserId and ResultValue in constructor
var myResultSequence =
gameInfo.Select(x => new MyResult(x.UserId, x.MatchesWon.ToString()));
Refactor only if you see the selects getting duplicated too much.
This is one possible way without using reflection:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class GameInfo
{
public int UserId { get; set; }
public int MatchesWon { get; set; }
public long BulletsFired { get; set; }
public string LastLevelVisited { get; set; }
// thousands more of these
}
public class MyResult
{
public int UserId { get; set; } // user id from above object
public string ResultValue { get; set; } // one of the value fields from above with .ToString() executed on it
}
public enum DataType
{
MatchesWon = 1,
BulletsFired = 2,
// add more as needed
}
class Program
{
private static Dictionary<DataType, Func<GameInfo, object>> getDataFuncs
= new Dictionary<DataType, Func<GameInfo, object>>
{
{ DataType.MatchesWon, info => info.MatchesWon },
{ DataType.BulletsFired, info => info.BulletsFired },
// add more as needed
};
public static IEnumerable<MyResult> GetMyResult(GameInfo[] gameInfos, DataType input)
{
var getDataFunc = getDataFuncs[input];
return gameInfos.Select(info => new MyResult()
{
UserId = info.UserId,
ResultValue = getDataFunc(info).ToString()
});
}
static void Main(string[] args)
{
var testData = new GameInfo[] {
new GameInfo { UserId="a", BulletsFired = 99, MatchesWon = 2 },
new GameInfo { UserId="b", BulletsFired = 0, MatchesWon = 0 },
};
// you can now easily select whatever data you need, in a type-safe manner
var dataToGet = DataType.MatchesWon;
var results = GetMyResult(testData, dataToGet);
}
}
}
Purely on the question of large switch statements, it is notable that there are 2 variants of the Cyclomatic Complexity metric in common use. The "original" counts each case statement as a branch and so it increments the complexity metric by 1 - which results in a very high value caused by many switches. The "variant" counts the switch statement as a single branch - this is effectively considering it as a sequence of non-branching statements, which is more in keeping with the "understandability" goal of controlling complexity.