This question already has answers here:
How to modify key in a dictionary in C#
(4 answers)
Closed 4 years ago.
I have a:
Dictionary<string, Dictionary<int, List<string>>> res = new Dictionary<string,
Dictionary<int, List<string>>>();
and I need to modify/change the int value of the nested Dictionary Key and keep all Dictionary values( List ) for the int Key.
If I understood everything correctly:
res[stringKey].Add(newKey, res[oldKey]);
res[stringKey].Remove(oldKey);
There is no native way to achieve this that I know of but you can try the following:
private void ModifyKey(int oldKey, int newKey, Dictionay<int, List<string>> dict)
{
var data = dict[oldKey];
// Now remove the previous data
dict.Remove(key);
try
{
dict.Add(newKey, data);
}
catch
{
// one already exists..., perhaps roll back or throw
}
}
You would then call the method as follows when you want to change the key:
// Assuming the dictionary is called myData
ModifyKey(5, 7, myData);
Related
This question already has answers here:
Proper way to initialize a C# dictionary with values
(9 answers)
Collection initialization
(5 answers)
Initialize Dictionary<string, List<string>>
(3 answers)
Closed 9 months ago.
I have a dictionary with the value being a list that contains VariableList objects like so
public VariableList {
public string VariableName;
public bool VariableBoolean;
}
Dictionary<string, List<VariableList>> myVariableDictionary;
How would I assign this Dictionary with multiple keys including all the objects in the List in one statement without using Add?
Assuming you already have instances of your VariableList class, you can do something like this:
myVariableDictionary = new Dictionary<string, List<VariableList>>
{
["string1"] = new List<VariableList> { variableList1, variableList2 ... },
["string2"] = new List<VariableList> { variableList3, variableList4 ... },
...
};
This question already has answers here:
How to add item to dictionary "Parallel loop safe"
(4 answers)
Dictionary weird behavior when adding item in Parallel.For [duplicate]
(3 answers)
Closed 12 months ago.
In the below code am using Parallel.ForEach to get the data of each item in my collection and store the response in the dictionary. But, in the dictionary the key and values are mismatched. Response of 1st item, is stored in the name of 2nd Item or 3rd item name.
Dictionary<string, object> keyValues = new Dictionary<string, object>();
Parallel.ForEach(myCollection, item =>
{
var data = GetData(item);
if (!keyValues.ContainsKey(item))
{
keyValues.Add(item, data);
}
});
return keyValues;
Try to use ConcurrentDictionary, because Dictionary isn't thread-safe.
Replace the ContainsKey and Add method calls with TryAdd
This question already has answers here:
Get dictionary key by value
(11 answers)
Closed 4 years ago.
I have defined Enumand Dictionary as below.
Now in Dictionary, I want to get Key from Value using Linq
enum Devices
{
Fan,
Bulb,
Mobile,
Television
};
Dictionary<int, Devices> dctDevices = new Dictionary<int, Devices>()
{
{1, Devices.Fan},
{2, Devices.Bulb},
{3, Devices.Mobile},
{4, Devices.Television}
};
I want result like below. I need concrete method named below.
int key = GetKeyFromValue(Devices.Bulb);
Please suggest me the best way to perform this. Thanks in advance
The method could look like:
int GetKeyFromValue(Devices device)
{
return dctDevices.Keys
.Where(k => dctDevices[k] == device)
.DefaultIfEmpty( -1 ) // or whatever "not found"-value
.First();
}
or a generic extension method for any type:
public static TKey GetKeyByBalue<TKey, TValue>(this IDictionary<TKey, TValue> dict, TValue value, TKey notFoundKey, IEqualityComparer<TValue> comparer = null)
{
if (comparer == null)
comparer = EqualityComparer<TValue>.Default;
return dict.Keys.Where(k => comparer.Equals(dict[k], value)).DefaultIfEmpty(notFoundKey).First();
}
Note that you should use another dictionary if you want to lookup that value often:
Dictionary<Devices, int> DeviceKeys = new Dictionary<Devices, int>()
{
{Devices.Fan, 1}, // ...
};
Then the code becomes more efficient:
int key = DeviceKeys[Devices.Bulb];
Or create a custom class Device which encapsulates the ID and the Devices (and other things):
You can do it like below:
dctDevices.AsEnumerable().Where(p => p.Value == Devices.Bulb).FirstOrDefault().Key;
This question already has answers here:
Convert Linq Query Result to Dictionary
(4 answers)
Closed 8 years ago.
Is it possible to use LINQ to get data from DB and store it in Dictionary.
I can do LINQ and store it in a List<Class_B> and then iterate through the list and store it in Dictonary<Class_A,List<Class_B>>. But is it possible to directly store in the Dictionary?
System.Linq.Enumerable has a ToDictionary method.
Here's an example from dotnetperls.com:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Example integer array.
int[] values = new int[] { 1, 3, 5, 7 };
// First argument is the key, second the value.
Dictionary<int, bool> dictionary = values.ToDictionary(v => v, v => true);
// Display all keys and values.
foreach (KeyValuePair<int, bool> pair in dictionary)
{
Console.WriteLine(pair);
}
}
}
This question already has answers here:
Multi Value Dictionary?
(10 answers)
Closed 8 years ago.
How can I store many different values in Dictionary under one key?
I have a code here:
Dictionary<string, DateTime> SearchDate = new Dictionary<string, DateTime>();
SearchDate.Add("RestDate", Convert.ToDateTime("02/01/2013"));
SearchDate.Add("RestDate", Convert.ToDateTime("02/28/2013"));
but in Dictionary i learned that only one unique key is allowed, so my code is producing error.
The simplest way is to make a Dictionary of some sort of container, for example
Dictionary<string,HashSet<DateTime>>
or
Dictionary<string,List<DateTime>>
Use Dictionary<string, List<DateTime>>. Access the list by the key, and then add the new item to the list.
Dictionary<string, List<DateTime>> SearchDate =
new Dictionary<string, List<DateTime>>();
...
public void AddItem(string key, DateTime dateItem)
{
var listForKey = SearchDate[key];
if(listForKey == null)
{
listForKey = new List<DateTime>();
}
listForKey.Add(dateItem);
}
You may try using a Lookup Class. To create it you may use Tuple Class:
var l = new List<Tuple<string,DateTime>>();
l.Add(new Tuple<string,DateTime>("RestDate", Convert.ToDateTime("02/01/2013")));
l.Add(new Tuple<string,DateTime>("RestDate", Convert.ToDateTime("02/28/2013")));
var lookup = l.ToLookup(i=>i.Item1);
However, if you need to modify the lookup, you'll have to modify the original list of tuples and update the lookup from it. So, it depends on how often this collection tends to change.
You can use Lookup class if you are using .NET 3.5