Concatenate two Dictionaries [duplicate] - c#

This question already has answers here:
Merging dictionaries in C#
(29 answers)
Closed 9 years ago.
Given some Dictionaries
Dictionary<string, string> GroupNames = new Dictionary<string, string>();
Dictionary<string, string> AddedGroupNames = new Dictionary<string, string>();
I am unable to merge them into one:
GroupNames = GroupNames.Concat(AddedGroupNames);
because "the type can't be implicitly converted". I believe (and my code proves me true) their type is the same - what am I overlooking?

I think you defined your GroupNames as Dictionary<string,string>, so you need to add ToDictionary like this:
GroupNames = GroupNames.Concat(AddedGroupNames)
.ToDictionary(x=>x.Key,x=>x.Value);
Note that 2 original dictionaries would have different keys, otherwise we need some rule to merge them correctly.

Related

Getting Collection text while serializing List<string> inside a Dictionary using JsonConvert in C# [duplicate]

This question already has answers here:
How can I serialize/deserialize a dictionary with custom keys using Json.Net?
(4 answers)
Closed 6 months ago.
So I have the following data structure defined in my program:
Dictionary<string, Dictionary<List<string>, int>> myTopDict = new Dictionary<string, Dictionary<List<string>, int>>();
Dictionary<List<string>, int> myInnerDict = new Dictionary<List<string>, int>();
int myIntValue=1;
List<string> myListValue=new List<string>();
myListValue.Add("Example Text 1");
myListValue.Add("Example Text 2");
//Here I add to my inner dictionary
myInnerDict.Add(myListValue, myIntValue);
//And finally adding to top dictionary
myTopDict.Add("My Data Set", myInnerDict);
//Serialize here
string result = JsonConvert.SerializeObject(myTopDict);
When I serialize the data structure, I am getting Collection text in the string as shown below:
What am I doing wrong here? Why I am not able to see my data in the serialized result?
For me the main problem that you have in your code is that you are using inside the dictionary as a key a list of string. That's why it's appering like that when you serialize the json
I don't know the expected Json result that you want. But if the idea is to have a collection of values, so change the Dictionary<string, Dictionary<List, int>> to Dictionary<string, Dictionary<string, List>>
Then the serialization will work different
Again, I really don't know the expected output or if that code is what you really want.

Adding value to a Dictionary in Parallel.ForEach [duplicate]

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

Best way to convert a dictionary to list in C# [duplicate]

This question already has answers here:
Convert dictionary values to list using linq
(3 answers)
Closed 8 years ago.
I am having some difficulties to convert a dictionary into a list.
var dic = new Dictionary<string, List<Tuple<DateTime, double>>>();
var list = new List<Tuple<DateTime, double>>();
list = dic.ToList(); // Cannot convert...
dict.ToList() will return collection of KeyValuePair<string, List<Tuple<DateTime, double>>().
If you want to hold all value's collection items in inside one list (flatten values) you need SelectMany:
list = dict.SelectMany(pair => pair.Value).ToList();

Dictionary with multiple values for each key? [duplicate]

This question already has answers here:
C# dictionary - one key, many values
(15 answers)
Closed 8 years ago.
I want the functionality of a Dictionary, but I want to store multiple values for each key. How can this be done in .NET/C#? Is there any built in collection that supports this scenario?
If I do the following:
collection.Add("key1", new Order(1));
collection.Add("key1", new Order(2));
collection.Add("key1", new Order(3));
collection.Add("key2", new Order(4));
Then running the following should return 3 orders.
collection["key1"];
Simple: Use Dictionary<string,List<Order>>
You may use lists for this purpose, if the number of orders per key needs to be variable.
collection.Add("key1"), new List<order>(){new Order(1), new Order(2)});
I would recommend using a List, Set, or Dictionary as appropriate for your Value in your Dictionary.
For example, you might do:
Dictionary<string, List<string>>
You should think about this in a different way. The Dictionary can hold a list of Orders rather than just a single one, like so:
var collection = Dictionary<string,List<Order>>();
collection.Add("key1", new List<Order>(new { new Order(1), new Order(2), new Order(3) });
collection.Add("key2", new Order(4));
Try this
Dictionary<string,order[] order> dict = new Dictionary<string,order[] order>();
how to access :
order[] orderArray = dict["key1"];
order order1 = orderArray[1] ;
order order2 = orderArray[2] ;
and goes on...

One key and many different values in Dictionary [duplicate]

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

Categories