Enum index by Value - c#

[FlagsAttribute]
public enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 };
I have an enum as show. I want the ability to get say Colors.Blue is at index 2, index staring from 0.I want to get the index number passing in Colors.Whatever? Can someone post me some snippets...

Try this one:
int index = Array.IndexOf(Enum.GetValues(typeof(Colors )), Colors.Green);

Assuming that each color uses a single bit as value, you can just locate the index of that bit.
public int GetIndex(Colors color) {
int value = (int)colors;
int index = 0;
while (value > 0) {
value >>= 1;
index++;
}
return index;
}
Note that the index of bits is normally zero based, but here you get a one based index.
If you want a zero based index, you would get the index two for blue, not three as you stated in the question. Just start with index = -1; if that is the result that you desire.

Can't really understand your question, but is this what you mean:
var blue = (Colors)Enum.GetValues(typeof(Colors))[2];

I don't know why you need it , but one way to do that is
Colors c = (Colors)Enum.Parse(typeof(Colors), Enum.GetNames(typeof(Colors))[index]);

This is the easiest solution I found. Works fine with flags w/o bothering with bytes operations.
Array eVals = Enum.GetValues(typeof(MyEnum));
MyEnum eVal = (MyEnum)eVals.GetValue(iIndex);

I got this working after doing it like this:
return (Status)Enum.GetValues(typeof(Status)).GetValue(this.EvaluationStatusId);

I am using the following code, and it is working:
int index=(int)Enum.Parse(typeof(Colors), "Green");

Related

Index outside the bounds of the array error

I am coding an algorithm and I am using arrays of custom data and if it looks a bit strange is that I am coding the algorithm for a futures trading platform and so they may have functions that don't look standard C#.
I'm trying to Resize my arrays because I need them resized every time a new value is found to be added and then I use the SetValue sometimes to replace the last value found when a better one is found again within the next 5 values after the last value was set.
Trouble is, when I debug it in Visual Studio, it stops at line after ArrayResize and when I hover over the LastLSwDMIpriceBar[k], it shows the k = 0, just as I expected it to be, as it would be the first element in the array of one, so what Index is then outside the bounds of the array?
The way I understand and hoped the code to work is this: when the conditions met are by setting LSwDMIbool to true, the array is resized from 0 to 1 element and the element with index [0] is then set as LastLSwDMIpriceBar[k]. Am I wrong about this?
Any help would be greatly appreciated.
private int k, l;
private int[] LastLSwDMIpriceBar;
LastLSwDMIpriceBar = new int [1];
.....
if (LSwDMIbool)
{
lastLSwDMIbar = CurrentBar - 2 - LowestBar(LSwDMI, 5);
LastLSwDMI[0] = DMI(Closes[2], Convert.ToInt32(DmiPeriod)).Values[0].GetValueAt(lastLSwDMIbar);
Array.Resize(ref LastLSwDMIpriceBar, l++);
LastLSwDMIpriceBar[k] = CurrentBar - LowestBar(Lows[2], 5);
k++;
LSwDMIprice[0] = Lows[2].GetValueAt(LastLSwDMIpriceBar[k]);
}
......
if(!LSwDMIbool)
{
for (int LastBar = CurrentBar - 1; IsFirstTickOfBar && LastBar <= lastLSwDMIbar + 5; LastBar++)
LastLSwDMIpriceBar.SetValue((CurrentBar - LowestBar(Lows[2], 5)), k);
}
You may find this helpful:
https://stackoverflow.com/a/24858/12343726
I believe you want ++l instead of l++ so that the new value of l is used when resizing the array. I suspect that l is zero the first time Array.Resize is called so the array is being resized to zero.
I'm trying to Resize my arrays because I need them resized every time a new value is found to be added
Don't use an array for this!
Instead, use a List<T>.
private int k, l;
private List<int> LastLSwDMIpriceBar = new List<int>();
.....
if (LSwDMIbool)
{
lastLSwDMIbar = CurrentBar - 2 - LowestBar(LSwDMI, 5);
LastLSwDMI[0] = DMI(Closes[2], Convert.ToInt32(DmiPeriod)).Values[0][lastLSwDMIbar];
var newValue = CurrentBar - LowestBar(Lows[2], 5);
LastLSwDMIpriceBar.Add(newValue);
k++;
LSwDMIprice[0] = Lows[2][newValue];
}
......
if(!LSwDMIbool)
{
for (int LastBar = CurrentBar - 1; IsFirstTickOfBar && LastBar <= lastLSwDMIbar + 5; LastBar++)
LastLSwDMIpriceBar[k] = CurrentBar - LowestBar(Lows[2], 5));
}

Use an integer to test a combination of enum values

I have seen something like this in practice before, but I cannot find out what the name of this technique is called to be able to google it.
I want to achieve this:
public enum Directions
{
Top = 1,
Right = 2,
Bottom = 4,
Left = 8
}
And then generate a random combination of those directions:
int combinationOfDirections = Random.Range(1, 15);
.. so the minimum could be 1, and the max 15 (1 + 2 + 4 + 8).
What method could I use to test which combination of top, right, bottom and left were picked. Something like:
// 'includes' is just the English version of what I want to do
if(combinationOfDirections includes Directions.Bottom)
I'm sure it was something using a '|' or an '&'.. any help would be hot!
Thanks
You can do this to check if a direction was included:
public static bool isDirectionAvailable(Directions direction, int value)
{
return ((int)direction & value) != 0;
}
If you have a variable like that:
var dirs = (Directions)combinationsOfDirections;
You can check if a single directions is contained by using the HasFlag() method:
bool hasTop = dirs.HasFlag(Directions.Top);
To check if the values is exactly a specified combination, you can do:
bool isExactlyTopAndBottom = dirs == Directions.Top | Directions.Bottom;

How to cycle through an (n by 12) 2D array

I have a 2-D array (with dimensions magnitudes n by 5), which I'm picturing in my head like this (each box is an element of the array):
(http://tr1.cbsistatic.com/hub/i/2015/05/07/b1ff8c33-f492-11e4-940f-14feb5cc3d2a/12039.jpg)
In this image, n is 3. I.e, n is the number of columns, 5 is the number of rows in my array.
I want to find an efficient way to iterate (i.e walk) through every path that leads from any cell in the left most column, to any cell in right most column, choosing one cell from every column in between.
It cannot be simply solved by n nested loops, because n is only determined at run time.
I think this means recursion is likely the best way forward, but can't picture how to begin theoretically.
Can you offer some advice as to how to cycle through every path. It seems simple enough and I can't tell what I'm doing wrong. Even just a theoretical explanation without any code will be very much appreciated.
I'm coding in C#, Visual Studio in case that helps.
UPDATE:: resolved using code below from http://www.introprogramming.info/english-intro-csharp-book/read-online/chapter-10-recursion/#_Toc362296468
static void NestedLoops(int currentLoop)
{
if (currentLoop == numberOfLoops)
{
return;
}
for (int counter=1; counter<=numberOfIterations; counter++)
{
loops[currentLoop] = counter;
NestedLoops(currentLoop + 1);
}
}
This is a factorial problem and so you might run quite quickly into memory or value limits issues.
Took some code from this SO post by Diego.
class Program
{
static void Main(string[] args)
{
int n = 5;
int r = 5;
var combinations = Math.Pow(r, n);
var list = new List<string>();
for (Int64 i = 1; i < combinations; i++)
{
var s = LongToBase(i);
var fill = n - s.Length;
list.Add(new String('0', fill) + s);
}
// list contains all your paths now
Console.ReadKey();
}
private static readonly char[] BaseChars = "01234".ToCharArray();
public static string LongToBase(long value)
{
long targetBase = BaseChars.Length;
char[] buffer = new char[Math.Max((int)Math.Ceiling(Math.Log(value + 1, targetBase)), 1)];
var i = (long)buffer.Length;
do
{
buffer[--i] = BaseChars[value % targetBase];
value = value / targetBase;
}
while (value > 0);
return new string(buffer);
}
}
list will contain a list of numbers expressed in base 5 which can be used to found out the path. for example "00123" means first cell, then first cell then second cell, then third cell and finall fourth cell.
Resolved:: see the code posted in the edited question above, and the link to a recursion tutorial, where it takes you through using recursion to simulate N nested, iterative loops.

how to compare values inside a list with each other in c#

any one to help me solving this problem of mine?
I want to find biggest value inside a list inserted by keyboard something like this:
here it can be done by array:
int[] values = new int[10];
for (int i = 0; i < values.Length; i++)
{
values[i] = (int) (textbox.Text);
}
//to campare them
int bigValue=0;
for(int j=0;j<values.Lenght;j++)
{
if(bigValue<values[j])
{
bigValue==values[j];
}
}
////////////////////////////////
but in my code I have to use List I have filled the list but now I don't know the way to compare its values with each other to find the lowest and biggest one:
List<int> values= new List<int>();
values.Add((int)(textbox.Text));
Theres already built in functions for it, Max and Min:
int maxValue = values.Max();
int minValue = values.Min();
Your original function would work as well, substituting Count for Length, as indexing works with lists as well.
Use LINQ Min & Max functions:-
int LowestNumber = values.Min();
int HighestNumber = values.Max();
If you say you also need to use the list later in your program I guess you could find useful just to have it sorted.
values.Sort((value1, value2) => value1.CompareTo(value2));
With this option, minValue would be values[0] although the recomended way to find it is using the built in function as they have already mentioned.
You could just say something like this, which will work for any IEnumerable<int>, whether it's an int[], a List<int> or something else:
int? max = null ;
foreach( int value in someList )
{
max = (max??value) > value : (max??value) ;
}
At the end of this, If the list was empty, max will be null; otherwise max will have the highest value in the list.

How to filter an array to remove wrong values (like noise)?

I have a measurement array of 1024 values. But in this array are some values wrong like noise/peaks. The array is normally like sinus so all values should be in a good line.
How can i create a filter to the array to remove these peaks and noise?
I heard something of an algorithm that compares always three values and creates the mean-value of it but I can't find an example of this.
The wrong values are "peaks" which are bigger than the value before so it is perhaps easier if i just compare the value with the value before for a given "Offset"?
But how to do this?
public int FilterArray(double[] Values, double Offset, out double[] Results)
{
int ArrLength = Values.Length;
Results = new double[ArrLength];
for (int i = 0; i < ArrLength; i++)
Values[i] = 0;
try
{
for (int i = 0; i < ArrLength; i++)
{
if (Values[i+1] + Offset) > (Values[i]
{
// here someting is needed
}
else
{
// nothing to do if next value is ok
}
}
}
return 0;
}
Thanks for all help
I suggest to use a List instead of an Array. If you need an Array to process your data you can use the ToArray() Method but removing/filtering items from a List is way more easy than resizing Arrays.
It seems you heard about Median Filter (due to phrase that compares always three values phrase). It works good when you have to remove rare peaks.
Example: for data point triplet [3, 100, 7] algorithm finds that median (not mean!) value of this triplet is 7, and (100) data point is replaced by (7) value.
public int FilterArray(List<double> Values, double Offset, out double[] Results)
{
foreach(double value in new List<double>(Values))
{
// some logic
Values.Remove(value);
}
return 0; //??
}

Categories