How can I loop in 2D grid decision tree in C#?
I have a list of objects I m开发者_开发知识库ust set a property based on two criteria the 2D grid looks like this:
Property 2\Property 1 B<80 80<B<100 100<B<120 B>120
A < 100 None Red Orange Orange
100 < A < 120 None Red Orange Green
120 < A < 140 None Red Green Green
140 < A None Orange Green Green
Is there a good way to loop Property 1 and Property 2 to dynamically set the object property? It is a possibility that in the future we add few criteria and I guess that doing multiple ifs isn't a good solution. I'm trying to avoid redundant code.
Thanks
I would recommend using an array lookup if you suspect things will change frequently. It would be best to load the data from a database or external file (to make configuration easy), but here I have hard coded the arrays:
int[] alimits = new int[] { 100, 120, 140, int.MaxValue };
int[] blimits = new int[] { 80, 100, 120, int.MaxValue };
int aval = 125;
int bval = 110;
int aindex = 0;
for (int i = 0; i < alimits.Count(); i++)
if (aval < alimits[i])
aindex = i;
int bindex = 0;
for (int i = 0; i < blimits.Count(); i++)
if (bval < blimits[i])
bindex = i;
string[,] values = new string[,] {
{"None", "Red", "Orange", "Orange"},
{"None", "Red", "Orange", "Green"},
{"None", "Red", "Green", "Green"},
{"None", "Orange", "Green", "Green"}};
This is untested, but should give you the basic idea. You get the result as values[aindex, bindex]
.
If we could convert the 2 conditions for A and B into a system with a scale of 0-3:
if A<100 -> Ascale = 0
else if A<120 -> Ascale = 1
etc.
and for B:
if B<80 -> Bscale = 0
else if B<100 -> Bscale = 1
etc.
Then we could use a 2d array for looking up the correct output response:
out = arrayname[Ascale][Bscale];
But I don't think this saves anything over simply hard-coding it as ifs, when only the possibility of a few extra ones, I think that hard-coding is the best solution for this.
class AbstractSetter { void SetObjectProperty(); }
class SetterLessThen100 : AbstractSettter { /* Implement code for the A<100 case */}
Implement list of setter objects that acts over the object for every case available. Add all of them to the AbstractSetters collection, iterate over it and call SetProperty() abstract method( thow overload on every concrete object). And in the future if you have some other condition to add, it's enough to implement new Setter and add it to the AbstractSetters collection.
Sorry , I have not enough time to write all code, hope it's clear. Good luck.
精彩评论