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

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

Related

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();

Find missing element in in dictionary from relative hashset [duplicate]

This question already has answers here:
How can I check if a HashSet contains an item using the hash of the item?
(2 answers)
Closed 8 years ago.
I'm beginner in C#.. I'm in a situation where I have a dictionary of
var enteries = new Dictionary<int, Entry>();
and I'm iterating over it by
foreach (KeyValuePair<int, Entry> entry in enteries)
I have a hashset<int> that has all keys like 1,2,3. Sometimes the dictionary is missing a key, how would I know if the current key that I'm iterating of over in the dictionary is missing from the hashset ?
Basically I'm trying to write CVS file and I need to know if if there is key is missing, so that I can write some empty row for that id.
I also want things to be sorted..
Looks like there is a misunderstanding:
Suppose enteries have keys, 238, 260
hashset has 238,260,250
How would I relate when I iterate over each key,pair in the dictionary, that there is a missing element, which is 250, and I should output something for example.
The simplest code won't be the most efficient, but will work; union the set of keys together and then iterate that:
foreach (int key in enteries.Keys.Union(yourHashSet)) {
Entry entry;
if (enteries.TryGetValue(key, out entry)) {
// The key is in the dictionary; the entry variable contains the value.
} else {
// The key is not in the dictionary.
}
}
If you want to sort the keys, just apply this operation after the union:
foreach (int key in enteries.Keys.Union(yourHashSet).OrderBy(i => i)) {
how would I know if the current key that I'm iterating of over in the
dictionary is missing from the hashset ?
Assuming you've got a HashSet<int> hashSet instance you could use the Contains method to determine whether an integer value is contained within this hashset and act accordingly:
HashSet<int> hashSet = ...
foreach (KeyValuePair<int, Entry> entry in enteries)
{
if (hashSet.Contains(entry.Key))
{
// The current key is contained within the hashSet
}
else
{
// The current key is not contained within the hashSet
}
}
Change your point of view.
As I understand in your HashSet is every needed Key. So iterate through the HashSet and find the key to every HashSet-Entry in the Dictionary.

c# Dictionary<string,string> how to loop through items without knowing key [duplicate]

This question already has answers here:
How to iterate over a dictionary?
(29 answers)
Closed 8 years ago.
I have a:
var selectedDates = new Dictionary<string, string>();
selectedDates.Add("2014-06-21", DateTime.Now.ToLongDateString());
selectedDates.Add("2014-07-21", DateTime.Now.AddDays(5).ToLongDateString());
selectedDates.Add("2014-08-21", DateTime.Now.AddDays(9).ToLongDateString());
selectedDates.Add("2014-09-21", DateTime.Now.AddDays(14).ToLongDateString());
How can I loop trough items without knowing the key?
For example I want to get the value of the item[0]
If I do:
var item = selectedDates[0].value; // I get an error
How can I loop trough items without knowing the key?
For example I want to get the value of the item[0]
You want to treat the dictionary as (ordered) collection similar to a list or array and get the first item in it?
You can because a Dictionary<string, string> is an IEnumerable<KeyValuePair<string, string>> implicitly. Just use First or FirstOrDefault:
string valueAtFirstPosition = selectedDates.First().Value;
However, note that a dictionary is not meant to be used as as an ordered collection. It is a collection which can be used to fast-lookup a value by a key. But you can enumerate it anyway.
foreach(KeyValuePair<string, string>keyVal in selectedDates)
{
Console.WriteLine("Key: {0} Value: {1}", keyVal.Key, keyVal.Value);
}
You should simply not rely on that order. I think in the current implementation the order is stable as long as you don't delete items. Read
Read: Why is a Dictionary “not ordered”?
try this
foreach (string key in selectedDates.Keys)
{
var item = selectedDates[key];
}
It's simple, loop trough it with a foreach or to get a specific index do:
var date = selectedDates.ElementAt(0).Value;
Let me put together two things for you. Firstly, you can loop or use LINQ to access elements, just as you could do it in a list as well:
var dict = new Dictionary<string, string>();
// loop
foreach (var item in dict)
{
var key = item.Key;
var value = item.Value;
}
// "first" (see below)
var firstItem = dict.First();
However, be aware that what you're referring to as the first item can be pretty much any item in the Dictionary. Dictionaries store elements in any order that is convenient for a lookup (so do sets).
This order is known for some implementations, but lists or arrays might fit better when the order of the elements is important. A Dictionary in .NET is an implementation of a hash table data structure (tree map is another map implementation).
try this :
foreach(var key in selectedDates.Keys)
{
var value = selectedDates[key];
}
Use this overload of Where:
var result = selectedDates.Where((d,i)=>i==0);
Try:
foreach (var date in selectedDates)
{
var item = date.Value;
}

Concatenate two Dictionaries [duplicate]

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.

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