Dictionary<string, int> to List<Dictionary<string, int>> in c# - c#

Is there a clean method to do this?
I tried
List<Dictionary<string, int>> myList = new List<Dictionary<string, int>>();
myList = myDict.ToList();
But that doesn't work, I'm looking for something similar to above if that is possible?

There are two statements in your question.
Assuming first is correct then do
myList.Add(myDict);
But if your second statement is correct then your first statement should be
List<KeyValuePair<string, int>> myList = new List<KeyValuePair<string, int>>();

Code:
Dictionary<string, int> myDict = new Dictionary<string, int>();
myDict.Add("1", 1);
myDict.Add("2", 2);
myDict.Add("3", 3);
myDict.Add("4", 4);
myDict.Add("5", 5);
List<Dictionary<string, int>> myList = new List<Dictionary<string, int>>();
myList.Add(myDict);
Something like this?

I think you need something like this:
Dictionary<int, string> myDict = new Dictionary<int, string>();
myDict.Add(1, "one");
myDict.Add(2, "two");
myDict.Add(3, "three");
List<KeyValuePair<int, string>> myList = myDict.ToList();
And retrieve data in this way:
// example get key and value
var myKey = myList[0].Key;
var myVal = myList[0].Value;

Related

How to link a string key to a function in a c# dictionary

I am currently programming using Unity and C#, and I have trouble linking a string value to a function using a dictionary.
I think of a code looking like this :
private string name;
void function1()
{
// code
}
private Dictionary<string, ?function?> nameToFunction = new Dictionary<string, ?function?>();
// The part between interrogation marks being unknown to me
// Trying to call the function with the name
nameToFunction[name]
I am sorry if my question isn't relative, or if there are simpler solutions I haven't thought of, but I am starting to learn programming.
Thanks for your answers !
Here are some examples:
private Dictionary<string, Action> actionDict = new Dictionary<string, Action>();
private Dictionary<string, Action<int>> actionParamDict = new Dictionary<string, Action<int>>();
private Dictionary<string, Func<int>> funcDict = new Dictionary<string, Func<int>>();
private Dictionary<string, Func<int, string>> funcParamDict = new Dictionary<string, Func<int, string>>();
You use Action e.g. Action<input type1, input type 2> if not returning a value, and Func<input type1, input type2, output type> to return a value. Both are defined with multiple numbers of inputs. So you could do Func<int,int,int,bool> for example, and Action<int,int,bool,string,string>
Here's a few examples:
var dict = new Dictionary<string, Action>();
dict.Add("Hello", () => Console.WriteLine("Hello"));
dict.Add("Goodbye", () => Console.WriteLine("Goodbye"));
dict["Hello"]();
dict["Goodbye"]();
var dict2 = new Dictionary<string, Action<string>>();
dict2.Add("HelloName", (name) => Console.WriteLine($"Hello {name}"));
dict2["HelloName"]("Fred");
var dict3 = new Dictionary<string, Func<int, int, int>>();
dict3.Add("ADD", (n1, n2) => n1 + n2);
dict3.Add("SUBTRACT", (n1, n2) => n1 - n2);
Console.WriteLine($"{dict3["ADD"](5, 10)}");
Console.WriteLine($"{dict3["SUBTRACT"](10, 5)}");
//create dict with var objects s0, s1, s2 dynamically
Dictionary<String, Object> dictionary = new Dictionary<String, Object>();
for(int i=0; i<sWPaths.Length-1; i++) {
string name = String.Format("s{0}", i);
dictionary[name] = i.ToString();
}
foreach (string p in found){
//change to your desired variable using string.format method
if(dictionary.Contains[p]) {
dictionary[p] = found.ToString();
}
}

list of dictionaries order by value C#

How can I order by value in descending order following the dictionary list
List<Dictionary<int, int>> myList = new List<Dictionary<int, int>>();
Dictionary<int, int> obj = new Dictionary<int, int>();
obj.Add(1, 2);
myList.Add(obj);
myList.Add(obj);
Dictionary<int, int> obj2 = new Dictionary<int, int>();
obj2.Add(2, 4);
myList.Add(obj2);
Dictionary<int, int> obj3 = new Dictionary<int, int>();
obj3.Add(3, 3);
myList.Add(obj3);
myList.Add(obj3);
myList.Add(obj3);
expected output will be
[0][2,4],
[1][3,3],
[2][3,3],
[3][3,3],
[4][1,2],
[5][1,2]
you can do something like this
var orderedValues = myList
.SelectMany(x => x)
.OrderByDescending(x => x.Value)
.ToList();
and output the data
for (int i = 0; i < orderedValues.Count(); i++)
{
Console.WriteLine($"[{i}][{orderedValues[i].Key},{orderedValues[i].Value}]");
}

Simplest way to add all content of Dictionary<T1, T2> to another Dictionary<T1, T2> (equal types for key & value)?

Is there a simpler way to copy/add all content of source dictionary to destination Dictionary<T1, T2> object than using one of the two options in the sample below?
Dictionary<string, int> source = new Dictionary<string, int>(),
destination = new Dictionary<string, int>();
source.Add("Developers", 1);
source.Add("just", 2);
source.Add("wanna have", 3);
source.Add("FUN!", 4);
// Option 1 (feels like a hack):
//
source.All(delegate(KeyValuePair<string, int> p)
{
destination.Add(p.Key, p.Value);
return true;
});
// Option 2:
//
foreach (string k in source.Keys)
{
destination.Add(k, source[k]);
}
What I was looking for is something like .ForEach().
Yes, you can use the constructor:
Dictionary<string, int> destination = new Dictionary<string, int>(source);
If destination is already filled and you don't want to lose them as commented i'd use this:
foreach (var kv in source)
if (!destination.ContainsKey(kv.Key))
destination.Add(kv.Key, kv.Value);
You can use Concat:
Dictionary<string, int> dict1 = new Dictionary<string, int>();
dict1.Add("first", 1);
Dictionary<string, int> dict2 = new Dictionary<string, int>();
dict2.Add("second", 2);
dict2 = dict2.Concat(dict1).ToDictionary(k => k.Key, v => v.Value);
This of course doesn't really 'add' it to the dictionary, but replaces it by a new one. You can use Union to get rid of duplicates.
static void Main()
{
Dictionary<string, int> source = new Dictionary<string, int>();
Dictionary<string, int> destination = new Dictionary<string, int>();
destination.Add("Apple", 1);
destination.Add("Banana", 2);
foreach (var item in destination)
{
source.Add(item.Key, item.Value);
}
foreach (var item in destination)
{
Console.WriteLine("Key is {0} and value is {1}", item.Key, item.Value);
}
}

How to add values to Dictionary with a list of dictionaries inside

Hello I'm trying to add values to this complex object. I'm trying to turn this object into JSON using JSON.Net.
Dictionary<string, List<Dictionary<string, int>>> MyList
= new Dictionary<string, List<Dictionary<string, int>>>();
The end result should look something like this: {
"Documents": [
{
"Title": ,
"DatePublished": ,
"DocumentURL": ,
"ThumbnailURL": ,
"Abstract": ,
"Sector": "",
"Country": [
""
],
"Document Type": ""
}
I have tried this but didn't work:
MyList["Dictionary"][0].Add("test", 4);
If you have a Dictionary<string, int> dictA you can add items to this via
Dictionary<string, int> dictA = new Dictionary<string, int>();
dictA.Add("SomeString", 99);
Then to add this dictionary to your List<Dictionary<string, int>> use the following
List<Dictionary<string, int>> dictList = new List<Dictionary<string, int>>();
dictList.Add(dictA);
Now you can add this to your Dictionary<string, List<Dictionary<string, int>>> myList object via
Dictionary<string, List<Dictionary<string, int>>> myList =
new Dictionary<string, List<Dictionary<string, int>>>();
myList.Add("SomeString", dictList);
I hope this helps.
For what it's worth, here's a sample loop which shows how to use Dictionary.Add and the Collection Initalizer:
Dictionary<string, List<Dictionary<string, int>>> MyList =
new Dictionary<string, List<Dictionary<string, int>>>();
foreach (int i in Enumerable.Range(1, 100))
{
var list = new List<Dictionary<string, int>>();
foreach (int ii in Enumerable.Range(1, 100))
list.Add(new Dictionary<string, int>() { { "Item " + ii, ii } });
MyList.Add("Item " + i, list);
}
MyList.Add("key1", new List<Dictionary<string, int>());
MyList["key1"].Add(new Dictionary<String, int>());
etc.
Will need more detail from you to give much more than that I'm afraid.
Even though it looks complex, it really is quite simple:
Your dictionary takes keys of string, and values of List<Dictionary<string, int>>. So to add a value, that value should always be of type List<Dictionary<string, int>>.

getting rid of white space in List<string> that resides in Dictionary

I have a dictionary with a string as key and a List as value.
Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
So for each key there are several string values associated with the key.
The Problem is that the list values conytains some whitespace that I need to get rid of and what I do is passing the values of each list value to a different list using the trim() method and then after the loop assign it back to the original list.
List<string> lstNoWhite = new List<string>();
foreach (var kvp in dict)
{
for(int i = 0; i < kvp.Value.Count; i++)
{
lstNoWhite.Add(kvp.Value[i].Trim());
}
kvp.Value = lstNoWhite;
}
I do however get the error...along the lines of that the list cannot be assigned to as it is read only.
Which is a better way of getting rid of the whitespace?
Try this code:
// source dictionary
Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
// target dictionary
Dictionary<string, List<string>> target = new Dictionary<string, List<string>>();
// using LINQ extension methods
dict.ToList().ForEach(i =>
{
List<string> temp = i.Value.Select(x => x.Trim()).ToList();
target.Add(i.Key, temp);
});
You can slightly modify your code to get rid of intermediate list:
foreach (var kvp in dict)
{
for(int i = 0; i < kvp.Value.Count; i++)
{
kvp.Value[i] = kvp.Value[i].Trim();
}
}
This will trim all whitespace in all strings from lists
You can also do this:
Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
// var --> Dictionary<string, List<string>>
var trimmedDict = dict.ToDictionary(
keyValue => keyValue.Key, // The key
keyValue => keyValue.Value.Select(s => s.Trim()).ToList() // The value, trim all the strings in the value-list
);

Categories

Resources