How can I replace int values in a dictionary C# - 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.

Related

C#: Set integer for any given string

I want to list the cost for every of my Upgrades.
Example:
String:"Faster Shooting",int: 10
I want an easy way to set a specific int for any string from a long list and later get the int, by the string
Use a Dictionary<TKey,TValue>, which is a collection of key-value pairs. In this case, your key would be a string and your value an int:
var dict = new Dictionary<string, int>();
dict["Faster Shooting"] = 10; // add "Faster Shooting" key, set to value 10.
dict["Faster Shooting"] = 15; // update "Faster Shooting" key, set to value 15.
Console.WriteLine(dict["Faster Shooting"]); // print "Faster Shooting" value
It also exposes Add(), TryAdd(), and other convenient methods, see #Heinzi's answer for an alternative using Add().
I want an easy way to set a specific X for any Y from a long list and later get the X, by the Y.
There's a built-in .NET data structure for exactly this purpose: A dictionary (sometimes called map, hash map or associative array in other programming languages).
Code example:
var dic = new Dictionary<string, int>();
dic.Add("Foo", 3);
dic.Add("Bar", 4);
Console.WriteLine(dic["Foo"]); // prints 3
Further examples can be found in the documentation.

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

how to add data to enum in c# wpf

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
};

swapping two key/value pairs in Dictionary of C#

here is what I want to do.
there is a Dictionary having 54 key/value objects. I want the key/value pair at index i to be swapped with the key/value pair at index j...
int i=1; int j=3;
Dictionary<String, int> theDeck = new Dictionary<String, int>();
theDeck.Add("zero", 0);
theDeck.Add("one", 1);
theDeck.Add("two", 2);
theDeck.Add("three", 3);
KeyValuePair<String, int> p1 = theDeck.ElementAt(i);
KeyValuePair<String, int> p2 = theDeck.ElementAt(j);
theDeck.ElementAt(i) = p2; //THIS LINE DOES NOT WORK. WHAT IS ITS ALTERNATIVE
theDeck.ElementAt(j) = p1; //THIS LINE DOES NOT WORK. WHAT IS ITS ALTERNATIVE
Dictionary<,> instances don't have "indexes" - you shouldn't treat them as ordered at all. Any order you may happen to notice when iterating over entries should be seen as an implementation detail.
If you want a specific order, there are various different types you could use, depending on your requirements. For example, to sort based on the key you'd use SortedDictionary<,> or SortedList<,>. For arbitrary ordering, consider OrderedDictionary (which is unfortunately non-generic).
Do you definitely need a dictionary at all? Could you just use a List<KeyValuePair<string, int>> or perhaps a List<Card> where Card is a custom type? (I'm guessing at your use case - Card could be any type which represents everything in your entry.)
Make mirroring (the 2nd) dictionary, and use it as a key source. Combine in 3d dictionary, while processing.
Try this.This worked for me.
First convert dictionary to list then find indexes of objects to be swapped.After swapping convert list back to dictionary.
var list = someDictionary.ToList();
int indexA = list.FindIndex(objA=> (condition));
int indexB = list.FindIndex(objB => (condition));
list.SwapListEntries(indexA, indexB);
someDictionary=list.ToDictionary(obj => obj.Key, obj => obj.Value);

Removing blank space from the dictionary key name

I have a Dictionary with some key-value pairs stored in it. My problem is that in my dictionary, I have a blank space at the start of the key name, so for accessing the value, I have to use:
Pair[" Key"];
Is there any method where I can remove the starting whitespace, so I can access the value like:
Pair["Key"]
If you have a string, you can remove leading and trailing whitespace with key.Trim() (MSDN).
If you want to trim all the keys in your dictionary, you can do this:
dictionary = dictionary.ToDictionary(x => x.Key.Trim(), x => x.Value);
This has room for failure, though, if you have 2 keys that will trim to the same value. For example, it is valid to have a dictionary with keys " key" and "key ", but if you trim them all, you'll get an ArgumentException because you'd be trying to add the same key twice ("key").
Trimming your string is enough. Besides that you can also write a custom key comparer for your dictionary instead of trimming your string everytime you add or get something to/from your dictionary.
Dictionary<string, int> dict = new Dictionary<string, int>(new Comparer());
dict.Add("aa ", 10);
int i = dict[" aa"];
public class Comparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
return x.Trim().Equals(y.Trim());
}
public int GetHashCode(string obj)
{
return obj.Trim().GetHashCode();
}
}
Use string.Trim method:
var key = " Key".Trim();
Pair[key];

Categories

Resources