how to add data to enum in c# wpf - c#

OK so I have a list which contains few string data set,
i want to assign this list values to enum according ling
my code below
namespace ILS.VM.Config
{
public class loadPortDetails
{
public void Ports()
{
List<string> portnameLIST= new List<string>();
portnameLIST.add(31);
portnameLIST.add(25);
portnameLIST.add(66);
//BaudRate.Baud_11001 = ;
}
}
public enum BaudRate
{
Baud_FLOOR1,
Baud_FLOOR2,
Baud_FLOOR3,
Baud_NONE = 0
};
}
data in the list has to be given as a values to the enum
for example:
Baud_FLOOR1=should have the values from portlist (portnamelist[1])
Baud_FLOOR2=should have the values from portlist (portnamelist[2])

You can't add/change the enum value in runtime
If you need a key-value pairs, I suggest to use Dictionary
Update:
So if you need to store int FloorNumber -> string PortNumber relationship
you should create a dictionary
Dictionary<int, string> floorPortMap = new Dictionary<int, string>();
To add pair you should use Add method.
floorPortMap.Add(10, "777"); // adds the (10, "777") pair to the dictionary.
To update pair you should use [] operator like
floorPortMap[10] = "8888" // changes previous (10, "777") pair to (10, "888")

Note that unless the value is specifically assigned the first enum will have the value 0, so in your code both Baud_FLOOR1 and Baud_NONE would have the value 0.
If the values will not change at runtime - you can assign values like this :
public enum BaudRate
{
Baud_NONE, // assignment of zero to first enum not required
Baud_FLOOR1 = 31,
Baud_FLOOR2 = 25,
Baud_FLOOR3 = 66
};

Related

Using struct in dictionary as a value

Hi I have a struct and dictionary as below and I'm trying to add it as a custom value
like
public struct data_inv
{
//protected static int p;
public float inventory;
public float supply;
public float demand;
};
public static IDictionary<int, data_inv> inv_stored = new Dictionary<int, data_inv>();
and I have tried to add value to dictionary but when I try to add a value like inv_stored[1].demand = 4;
its gives System.Collections.Generic.KeyNotFoundException: 'The given key was not present in the Dictionary.' exception. I'm new to coding, could any explain what im doing wrong
If you want to use a struct instead of a class, write this instead of inv_stored[1].demand = 4 (updated based on comments):
public struct data_inv
{
public float Inventory;
public float Supply;
public float Demand;
public data_inv(int demand)
{
Inventory = 0;
Supply = 0;
Demand = demand;
}
};
// ....
IDictionary<int, data_inv> inv_stored = new Dictionary<int, data_inv>();
data_inv myData = new data_inv(4);
inv_stored.Add(1, myData);
This is a way to add keyValue to a Dictionary.
data_inv shouldn't be a struct. It's mutable, and structs shouldn't be mutable, it's not representing a single value. You should make it a class instead.
public class data_inv
{
//protected static int p;
public float inventory;
public float supply;
public float demand;
};
Implementation:
// Add new item into dictionary
inv_stored.Add(1, new data_inv()
{
inventory = 20,
supply = 10,
demand = 5
});
Console.WriteLine(inv_stored[1].demand); // 5
inv_stored[1].demand = 4;
Console.WriteLine(inv_stored[1].demand); // 4
Edit:
Print all elements each in one line:
foreach (var kvp in inv_stored)
{
Console.Write("bucket:{0} ", kvp.Key);
Console.Write("inventory:{0}, ", kvp.Value.inventory);
Console.Write("supply:{0}, ", kvp.Value.supply);
Console.WriteLine("demand:{0}", kvp.Value.demand);
}
Example output:
bucket:1 inventory:20, supply:10, demand:4
bucket:2 inventory:16, supply:9, demand:7
Print all elements into a table format:
var buckets = inv_stored.Keys;
var inventory = inv_stored.Values.Select(x => x.inventory);
var supply = inv_stored.Values.Select(x => x.supply);
var demand = inv_stored.Values.Select(x => x.demand);
Console.WriteLine("buckets:\t{0}", string.Join("\t", buckets));
Console.WriteLine("inventory:\t{0}", string.Join("\t", inventory));
Console.WriteLine("supply: \t{0}", string.Join("\t", supply));
Console.WriteLine("demand: \t{0}", string.Join("\t", demand));
Example Output:
buckets: 1 2 3
inventory: 20 16 56
supply: 10 9 44
demand: 4 7 23
There's multiple problems with your code.
First, you can create a new record in a dictionary by doing something like dict[key] = value;. However, you can not do dict[key].field = value;. The setter can be used with non-existent keys, the getter can't.
Second, while you can use structs as values in a dictionary, you cannot set their fields directly. Structs use value-type semantics by default (i.e. whenever you don't explicitly use ref or take a pointer), so any change you made this way would be done to a copy of the struct, not the actual value in the dictionary. You can use something like this:
var val = dict[key];
val.field = newFieldValue;
dict[key] = val;
Third, it's generally considered bad practice to use mutable structs, exactly because of these complications. Mutable structs only have place in highly optimised code and native interop, and they need to be carefully tested and monitored. Heck, even many automated refactorings can break code with mutable structs.

Check if the number is contained within Dictionary array C#

I have Dictionary that the key is an array of int, and the value is a string. How can I get the value by check if int is contained in the key array?
public static Dictionary<int[], string> MyDic = new Dictionary<int[], string>
{
{new int[]{2,25},"firstValue"},
{new int[]{3,91,315,322},"secondValue"}
};
I have :
int number=91;
string value=?;
I need the value will get "secondValue"
I think this is a bad design choice. If the numbers don't repeat between keys (as you said in your comment for the question) then just flatten the keys into a simple Dictionary<int,string>. Just have the different integers all be keys for the same strings.
For example:
Dictionary<int,string>
{
[2] = "firstValue",
[25] = "firstValue",
};
In order to not repeat the same values but as different objects you can place a reference there:
string firstValue = "firstValue";
Dictionary<int,string>
{
[2] = firstValue,
[25] = firstValue,
};
In this case changing the value's content (not for a string as it is immutable but if it was some other object) for one key will change for all.
Use contains and a foreach loop (more readable than some other solutions):
string value;
int number = 91;
foreach(KeyValuePair<int[], string> entry in MyDic)
{
if (entry.Key.Contains(number))
{
value = entry.Value;
}
}
However, maybe a dictionary isn't the right choice for this.
Check out Gilads answer for another structure that you could use
string value = MyDic.FirstOrDefault(x => x.Key.Contains(number)).Value;
? is not needed, can not apply ? operand to KeyValuePair
something like
value = MyDic.FirstOrDefault(x => x.Key.Contains(number)).Value;
will return the first occurrence or null

Will this array method keep updating the [0] index, or will it move the previous text back?

I have a method bringing in text every 600000 milliseconds, this is added to an array through the following method:
String[] namesArray = { };
Array.Resize(ref namesArray, namesArray.Length + 1);
namesArray[namesArray.Length - 1] = nameSplit;
I was curious, is this just replacing the array with the new text, or is it pushing the old index up to 1. Example if the text that came through was Jim, would this be placed in [0]. When the next comes through and it is "Harry", will "Jim" be pushed to 1 and "Harry" to [0]. Let me know if more code is required.
EDIT
Here is what your code is doing:
String[] namesArray = { }; // Create a new zero-element array.
Array.Resize(ref namesArray, namesArray.Length + 1); // Increase size of array by 1.
namesArray[namesArray.Length - 1] = nameSplit; // Assign to array's last element.
Thus, the end-result is that you would have a one-element array whose content is your nameSplit variable. This is equivalent to:
String[] namesArray = { nameSplit };
Subsequent calls will results in a new one-element array being created and assigned to namesArray.
Instead of manually resizing an array, consider using a List<T> instead. It's basically a self-resizing array. Instead of using two arrays, one for the names and another for the amounts, it's better to make a struct or class that groups a name and amount together, so you can use a single list:
public struct NameAndAmount
{
public string Name;
public int Amount;
public NameAndAmount(string name, int amount)
{
Name = name;
Amount = amount;
}
}
List<NameAndAmount> items = new List<NameAndAmount>();
items.Add(new NameAndAmount("test", 100));
However, if you need to perform lookups by name, you may want to use a Dictionary<TKey, TValue> instead, using the names as keys and the amounts as values:
Dictionary<string, int> items = new Dictionary<string, int>();
// Check if a name has been stored before:
if (items.ContainsKey(name))
int previousAmount = items[name];
// Store a name and amount:
items[name] = amount;

How can I replace int values in a dictionary C#

I am wondering how I could replace int values in a dictionary in C#.
The values would look something like this.
25,12
24,35
12,34
34,12
I was wondering how I could only replace one line. For example if I wanted to replace the first line with a new value of 12,12. And it wouldn't replace any of the other '12' values in the dictionary.
A Dictionary<TInt, TValue> makes use of what are known as indexers. In this case, these are used to access elements in the dictionary by key, hence:
dict[25] would return 12.
Now, according to what you want to do is to have a key of 12 and a value of 12. Unfortunately, you cannot replace entries in a dictionary by key, so what you must do is:
if(dict.ContainsKey(25))
{
dict.Remove(25);
}
if(!dict.ContainsKey(12))
{
dict.Add(12, 12);
}
Note: In the values you supplied, there is already a key-value pair with 12 as its key, so you would not be allowed to add 12,12 to the dictionary as if(!dict.ContainsKey(12)) would return false.
You cannot replace the first line with 12, 12 because there is another key value pair with 12 as it's key. And you cannot have duplicate keys in a dictionary.
Anyway you may do such things like this:
Dictionary<int, int> myDictionary = new Dictionary<int, int>();
myDictionary.Add(25, 12);
myDictionary.Add(24, 35);
//remove the old item
myDictionary.Remove(25);
//add the new item
myDictionary.Add(12, 12);
EDIT: if you are going to save some x,y positions I would suggest you creating a class named Point and use a List<Point>. Here is the code:
class Point
{
public double X {get; set;}
public double Y {get; set;}
public Point(double x, double y)
{
this.X = x;
this.Y = y;
}
}
Then:
List<Point> myList =new List<Point>();
myList.Add(new Point(25, 13));
In Dictionaries, the keys must be unique.
In case the key need not be unique, you could use a List<Tuple<int, int>> or List<CustomClass> with CustomClass containing two integer fields. Then you may add or replace the way you want.

Why can't we give names to properties in Tuples?

Is there a specific reason that we have to refer to the properties in a Tuple as Item1, Item2 etc. This just seems like a bad idea to me as they could easily get mixed up in your code. Wouldn't it be much more meaningful to be able to name your properties ie. Red, Green, Blue?
If you want names, don't use Tuples.
Anonymous type:
var t = new { Green = 1, Red = "nice" };
if (t.Green > 0) ....
The Tuple<...> classes are just normal C# classes. C# does not provide a way to have dynamically-named properties (aside from just using a Dictionary or a dynamic object like ExpandoObject). However, C# does provide something like what you want via anonymous types:
var x = new { Red = 10, Blue = 20, Green = 30 }
var sum = x.Red + x.Blue + x.Green;
The reason anonymous types work is that they are just a convenient syntax for defining a custom tuple class on the fly.
These have the advantage of acting like named tuples, but have the disadvantage of not being nameable by the programmer (so you can't make a method that explicitly returns an anonymous type).
If you want to do this then create a class with the appropriately named properties. A tuple is just a quick and dirty way of avoiding having to write a class or use out params when you want to return multiple values from a method.
A tuple is not supposed to contain any meaningful properties. It is just a disposable set of items bunched together in a group.
If you want meaningful property names, make a type with those properties. You can either write a class from scratch and use that class, or use anonymous types.
You could define the class like this (with generics) if you will always be partial to Red/Blue, otherwise, you can use anonymous types as suggested by others.
class RedBluePair<T1, T2>
{
private T1 _Red;
private T2 _Blue;
public RedBluePair(T1 red, T2 blue)
{
_Red = red;
_Blue = blue;
}
public T1 Red { get { return _Red;} }
public T2 Blue { get { return _Blue;} }
}
Reproducing my answer from this post as now it is possible to give names to properties in Tuples.
Starting C# v7.0 now it is possible to name the tuple properties which earlier used to default to names like Item1, Item2 and so on.
Naming the properties of Tuple Literals:
var myDetails = (MyName: "RBT_Yoga", MyAge: 22, MyFavoriteFood: "Dosa");
Console.WriteLine($"Name - {myDetails.MyName}, Age - {myDetails.MyAge}, Passion - {myDetails.MyFavoriteFood}");
The output on console:
Name - RBT_Yoga, Age - 22, Passion - Dosa
Returning Tuple (having named properties) from a method:
static void Main(string[] args)
{
var empInfo = GetEmpInfo();
Console.WriteLine($"Employee Details: {empInfo.firstName}, {empInfo.lastName}, {empInfo.computerName}, {empInfo.Salary}");
}
static (string firstName, string lastName, string computerName, int Salary) GetEmpInfo()
{
//This is hardcoded just for the demonstration. Ideally this data might be coming from some DB or web service call
return ("Rasik", "Bihari", "Rasik-PC", 1000);
}
The output on console:
Employee Details: Rasik, Bihari, Rasik-PC, 1000
Creating a list of Tuples having named properties
var tupleList = new List<(int Index, string Name)>
{
(1, "cow"),
(5, "chickens"),
(1, "airplane")
};
foreach (var tuple in tupleList)
Console.WriteLine($"{tuple.Index} - {tuple.Name}");
Output on console:
1 - cow
5 - chickens
1 - airplane
I hope I've covered everything. In case, there is anything which I've missed then please give me a feedback in comments.
Note: My code snippets are using string interpolation feature of C# v7 as detailed here.
Yes, You can name tuple properties from C# 7.0.
From this documentation,
You can explicitly specify the names of tuple fields either in a tuple initialization expression or in the definition of a tuple type, as the following example shows:
(int Red, int Green, int Blue) ColorRGB = (0, 0, 255);
// Or
var ColorRGB = (Red: 0, Green: 0, Blue: 255);
Or,
If you don't specify a field name, it may be inferred from the name of the corresponding variable in a tuple initialization expression, as the following example shows:
int Red = 0;
int Green = 0;
int Blue = 255;
var ColorRGB = (Red, Green, Blue);

Categories

Resources