C# dictionary pattern, which is best? - c#

Which of these patterns should be preferred over the other and why?
foreach(KeyValuePair<string, Dictionary<string, string>> data in
new Dictionary<string, Dictionary<string, string>> {
{"HtmlAttributes", this.HtmlAttributes},
{"Content", this.Content}
})
{
foreach(KeyValuePair<string, string> entry in data.Value)
{
// do something
}
}
or
Dictionary<string, Dictionary<string, string>> data = new Dictionary<string, Dictionary<string, string>>();
data.Add("HtmlAttributes", this.HtmlAttributes);
data.Add("Content", this.Content);
foreach(KeyValuePair<string, IDictionary<string, string>> entry in data)
{
// Do something
}
data.Clear(); // not sure if this is needed either
data = null; // gc object
Please don't answer with "use var", as I don't like using it.
Re: var (2 years later): I must add something to make this right. In retrospect, reading Eric Lipert's blog post about when and why to use var makes total sense. IF used appropriately, meaning not all the time, it makes perfect sense and it shortens the amount code one needs to read. On the matter of what initialization to use, well the object initializer is fine, but splitting up initialization from the foreach or other processing makes the code more readable.

I think the comments by Kent Boogaart and quakkels are right. var makes sense here. If I had to choose one of your two I'd say the 2nd is better as it's slightly easier to read.

I would prefer something in between your two versions: split creation and iteration, but use collection initializer.
Dictionary<string, Dictionary<string, string>> dicts =
new Dictionary<string, Dictionary<string, string>> {
{"HtmlAttributes", this.HtmlAttributes},
{"Content", this.Content}
});
foreach(KeyValuePair<string, Dictionary<string, string>> data in dicts)
{
foreach(KeyValuePair<string, string> entry in data.Value)
{
// do something
}
}
or equivalently (really, from the point of view of both the compiler and IDE, the following is exactly the same):
var dicts = new Dictionary<string, Dictionary<string, string>> {
{"HtmlAttributes", this.HtmlAttributes},
{"Content", this.Content}
});
foreach(var data in dicts)
{
foreach(var entry in data.Value)
{
// do something
}
}
Also, if you're using Dictionary just as a list of pairs, you could use either List<KeyValuePair<K, V>> or (on .Net 4) List<Tuple<T1, T2>>.

I think your second version is more readable. Given that you don't like to use var, that seems even more important as your first version kind of gives me a headache.
I also think that it's a little convoluted to mix the code that creates a collection with the code that loops through it.
So, for me, it's a matter of readability and I prefer the second version. But in the end, either one works.

Related

Asp.Net KeyValuePair<string, { } > does not contain definition or extension [duplicate]

I've seen a few different ways to iterate over a dictionary in C#. Is there a standard way?
foreach(KeyValuePair<string, string> entry in myDictionary)
{
// do something with entry.Value or entry.Key
}
If you are trying to use a generic Dictionary in C# like you would use an associative array in another language:
foreach(var item in myDictionary)
{
foo(item.Key);
bar(item.Value);
}
Or, if you only need to iterate over the collection of keys, use
foreach(var item in myDictionary.Keys)
{
foo(item);
}
And lastly, if you're only interested in the values:
foreach(var item in myDictionary.Values)
{
foo(item);
}
(Take note that the var keyword is an optional C# 3.0 and above feature, you could also use the exact type of your keys/values here)
In some cases you may need a counter that may be provided by for-loop implementation. For that, LINQ provides ElementAt which enables the following:
for (int index = 0; index < dictionary.Count; index++) {
var item = dictionary.ElementAt(index);
var itemKey = item.Key;
var itemValue = item.Value;
}
Depends on whether you're after the keys or the values...
From the MSDN Dictionary(TKey, TValue) Class description:
// When you use foreach to enumerate dictionary elements,
// the elements are retrieved as KeyValuePair objects.
Console.WriteLine();
foreach( KeyValuePair<string, string> kvp in openWith )
{
Console.WriteLine("Key = {0}, Value = {1}",
kvp.Key, kvp.Value);
}
// To get the values alone, use the Values property.
Dictionary<string, string>.ValueCollection valueColl =
openWith.Values;
// The elements of the ValueCollection are strongly typed
// with the type that was specified for dictionary values.
Console.WriteLine();
foreach( string s in valueColl )
{
Console.WriteLine("Value = {0}", s);
}
// To get the keys alone, use the Keys property.
Dictionary<string, string>.KeyCollection keyColl =
openWith.Keys;
// The elements of the KeyCollection are strongly typed
// with the type that was specified for dictionary keys.
Console.WriteLine();
foreach( string s in keyColl )
{
Console.WriteLine("Key = {0}", s);
}
Generally, asking for "the best way" without a specific context is like asking
what is the best color?
One the one hand, there are many colors and there's no best color. It depends on the need and often on taste, too.
On the other hand, there are many ways to iterate over a Dictionary in C# and there's no best way. It depends on the need and often on taste, too.
Most straightforward way
foreach (var kvp in items)
{
// key is kvp.Key
doStuff(kvp.Value)
}
If you need only the value (allows to call it item, more readable than kvp.Value).
foreach (var item in items.Values)
{
doStuff(item)
}
If you need a specific sort order
Generally, beginners are surprised about order of enumeration of a Dictionary.
LINQ provides a concise syntax that allows to specify order (and many other things), e.g.:
foreach (var kvp in items.OrderBy(kvp => kvp.Key))
{
// key is kvp.Key
doStuff(kvp.Value)
}
Again you might only need the value. LINQ also provides a concise solution to:
iterate directly on the value (allows to call it item, more readable than kvp.Value)
but sorted by the keys
Here it is:
foreach (var item in items.OrderBy(kvp => kvp.Key).Select(kvp => kvp.Value))
{
doStuff(item)
}
There are many more real-world use case you can do from these examples.
If you don't need a specific order, just stick to the "most straightforward way" (see above)!
C# 7.0 introduced Deconstructors and if you are using .NET Core 2.0+ Application, the struct KeyValuePair<> already include a Deconstruct() for you. So you can do:
var dic = new Dictionary<int, string>() { { 1, "One" }, { 2, "Two" }, { 3, "Three" } };
foreach (var (key, value) in dic) {
Console.WriteLine($"Item [{key}] = {value}");
}
//Or
foreach (var (_, value) in dic) {
Console.WriteLine($"Item [NO_ID] = {value}");
}
//Or
foreach ((int key, string value) in dic) {
Console.WriteLine($"Item [{key}] = {value}");
}
I would say foreach is the standard way, though it obviously depends on what you're looking for
foreach(var kvp in my_dictionary) {
...
}
Is that what you're looking for?
You can also try this on big dictionaries for multithreaded processing.
dictionary
.AsParallel()
.ForAll(pair =>
{
// Process pair.Key and pair.Value here
});
I appreciate this question has already had a lot of responses but I wanted to throw in a little research.
Iterating over a dictionary can be rather slow when compared with iterating over something like an array. In my tests an iteration over an array took 0.015003 seconds whereas an iteration over a dictionary (with the same number of elements) took 0.0365073 seconds that's 2.4 times as long! Although I have seen much bigger differences. For comparison a List was somewhere in between at 0.00215043 seconds.
However, that is like comparing apples and oranges. My point is that iterating over dictionaries is slow.
Dictionaries are optimised for lookups, so with that in mind I've created two methods. One simply does a foreach, the other iterates the keys then looks up.
public static string Normal(Dictionary<string, string> dictionary)
{
string value;
int count = 0;
foreach (var kvp in dictionary)
{
value = kvp.Value;
count++;
}
return "Normal";
}
This one loads the keys and iterates over them instead (I did also try pulling the keys into a string[] but the difference was negligible.
public static string Keys(Dictionary<string, string> dictionary)
{
string value;
int count = 0;
foreach (var key in dictionary.Keys)
{
value = dictionary[key];
count++;
}
return "Keys";
}
With this example the normal foreach test took 0.0310062 and the keys version took 0.2205441. Loading all the keys and iterating over all the lookups is clearly a LOT slower!
For a final test I've performed my iteration ten times to see if there are any benefits to using the keys here (by this point I was just curious):
Here's the RunTest method if that helps you visualise what's going on.
private static string RunTest<T>(T dictionary, Func<T, string> function)
{
DateTime start = DateTime.Now;
string name = null;
for (int i = 0; i < 10; i++)
{
name = function(dictionary);
}
DateTime end = DateTime.Now;
var duration = end.Subtract(start);
return string.Format("{0} took {1} seconds", name, duration.TotalSeconds);
}
Here the normal foreach run took 0.2820564 seconds (around ten times longer than a single iteration took - as you'd expect). The iteration over the keys took 2.2249449 seconds.
Edited To Add:
Reading some of the other answers made me question what would happen if I used Dictionary instead of Dictionary. In this example the array took 0.0120024 seconds, the list 0.0185037 seconds and the dictionary 0.0465093 seconds. It's reasonable to expect that the data type makes a difference on how much slower the dictionary is.
What are my Conclusions?
Avoid iterating over a dictionary if you can, they are substantially slower than iterating over an array with the same data in it.
If you do choose to iterate over a dictionary don't try to be too clever, although slower you could do a lot worse than using the standard foreach method.
As already pointed out on this answer, KeyValuePair<TKey, TValue> implements a Deconstruct method starting on .NET Core 2.0, .NET Standard 2.1 and .NET Framework 5.0 (preview).
With this, it's possible to iterate through a dictionary in a KeyValuePair agnostic way:
var dictionary = new Dictionary<int, string>();
// ...
foreach (var (key, value) in dictionary)
{
// ...
}
There are plenty of options. My personal favorite is by KeyValuePair
Dictionary<string, object> myDictionary = new Dictionary<string, object>();
// Populate your dictionary here
foreach (KeyValuePair<string,object> kvp in myDictionary)
{
// Do some interesting things
}
You can also use the Keys and Values Collections
With .NET Framework 4.7 one can use decomposition
var fruits = new Dictionary<string, int>();
...
foreach (var (fruit, number) in fruits)
{
Console.WriteLine(fruit + ": " + number);
}
To make this code work on lower C# versions, add System.ValueTuple NuGet package and write somewhere
public static class MyExtensions
{
public static void Deconstruct<T1, T2>(this KeyValuePair<T1, T2> tuple,
out T1 key, out T2 value)
{
key = tuple.Key;
value = tuple.Value;
}
}
As of C# 7, you can deconstruct objects into variables. I believe this to be the best way to iterate over a dictionary.
Example:
Create an extension method on KeyValuePair<TKey, TVal> that deconstructs it:
public static void Deconstruct<TKey, TVal>(this KeyValuePair<TKey, TVal> pair, out TKey key, out TVal value)
{
key = pair.Key;
value = pair.Value;
}
Iterate over any Dictionary<TKey, TVal> in the following manner
// Dictionary can be of any types, just using 'int' and 'string' as examples.
Dictionary<int, string> dict = new Dictionary<int, string>();
// Deconstructor gets called here.
foreach (var (key, value) in dict)
{
Console.WriteLine($"{key} : {value}");
}
foreach is fastest and if you only iterate over ___.Values, it is also faster
Using C# 7, add this extension method to any project of your solution:
public static class IDictionaryExtensions
{
public static IEnumerable<(TKey, TValue)> Tuples<TKey, TValue>(
this IDictionary<TKey, TValue> dict)
{
foreach (KeyValuePair<TKey, TValue> kvp in dict)
yield return (kvp.Key, kvp.Value);
}
}
And use this simple syntax
foreach (var(id, value) in dict.Tuples())
{
// your code using 'id' and 'value'
}
Or this one, if you prefer
foreach ((string id, object value) in dict.Tuples())
{
// your code using 'id' and 'value'
}
In place of the traditional
foreach (KeyValuePair<string, object> kvp in dict)
{
string id = kvp.Key;
object value = kvp.Value;
// your code using 'id' and 'value'
}
The extension method transforms the KeyValuePair of your IDictionary<TKey, TValue> into a strongly typed tuple, allowing you to use this new comfortable syntax.
It converts -just- the required dictionary entries to tuples, so it does NOT converts the whole dictionary to tuples, so there are no performance concerns related to that.
There is a only minor cost calling the extension method for creating a tuple in comparison with using the KeyValuePair directly, which should NOT be an issue if you are assigning the KeyValuePair's properties Key and Value to new loop variables anyway.
In practice, this new syntax suits very well for most cases, except for low-level ultra-high performance scenarios, where you still have the option to simply not use it on that specific spot.
Check this out: MSDN Blog - New features in C# 7
Simplest form to iterate a dictionary:
foreach(var item in myDictionary)
{
Console.WriteLine(item.Key);
Console.WriteLine(item.Value);
}
I found this method in the documentation for the DictionaryBase class on MSDN:
foreach (DictionaryEntry de in myDictionary)
{
//Do some stuff with de.Value or de.Key
}
This was the only one I was able to get functioning correctly in a class that inherited from the DictionaryBase.
Sometimes if you only needs the values to be enumerated, use the dictionary's value collection:
foreach(var value in dictionary.Values)
{
// do something with entry.Value only
}
Reported by this post which states it is the fastest method:
http://alexpinsker.blogspot.hk/2010/02/c-fastest-way-to-iterate-over.html
I know this is a very old question, but I created some extension methods that might be useful:
public static void ForEach<T, U>(this Dictionary<T, U> d, Action<KeyValuePair<T, U>> a)
{
foreach (KeyValuePair<T, U> p in d) { a(p); }
}
public static void ForEach<T, U>(this Dictionary<T, U>.KeyCollection k, Action<T> a)
{
foreach (T t in k) { a(t); }
}
public static void ForEach<T, U>(this Dictionary<T, U>.ValueCollection v, Action<U> a)
{
foreach (U u in v) { a(u); }
}
This way I can write code like this:
myDictionary.ForEach(pair => Console.Write($"key: {pair.Key}, value: {pair.Value}"));
myDictionary.Keys.ForEach(key => Console.Write(key););
myDictionary.Values.ForEach(value => Console.Write(value););
If you want to use a for loop, you can do as below:
var keyList=new List<string>(dictionary.Keys);
for (int i = 0; i < keyList.Count; i++)
{
var key= keyList[i];
var value = dictionary[key];
}
I will take the advantage of .NET 4.0+ and provide an updated answer to the originally accepted one:
foreach(var entry in MyDic)
{
// do something with entry.Value or entry.Key
}
If say, you want to iterate over the values collection by default, I believe you can implement IEnumerable<>, Where T is the type of the values object in the dictionary, and "this" is a Dictionary.
public new IEnumerator<T> GetEnumerator()
{
return this.Values.GetEnumerator();
}
The standard way to iterate over a Dictionary, according to official documentation on MSDN is:
foreach (DictionaryEntry entry in myDictionary)
{
//Read entry.Key and entry.Value here
}
I wrote an extension to loop over a dictionary.
public static class DictionaryExtension
{
public static void ForEach<T1, T2>(this Dictionary<T1, T2> dictionary, Action<T1, T2> action) {
foreach(KeyValuePair<T1, T2> keyValue in dictionary) {
action(keyValue.Key, keyValue.Value);
}
}
}
Then you can call
myDictionary.ForEach((x,y) => Console.WriteLine(x + " - " + y));
Dictionary< TKey, TValue > It is a generic collection class in c# and it stores the data in the key value format.Key must be unique and it can not be null whereas value can be duplicate and null.As each item in the dictionary is treated as KeyValuePair< TKey, TValue > structure representing a key and its value. and hence we should take the element type KeyValuePair< TKey, TValue> during the iteration of element.Below is the example.
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1,"One");
dict.Add(2,"Two");
dict.Add(3,"Three");
foreach (KeyValuePair<int, string> item in dict)
{
Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value);
}
The best answer is of course: Think, if you could use a more appropriate data structure than a dictionary if you plan to iterate over it- as Vikas Gupta mentioned already in the (beginning of the) discussion under the question. But that discussion as this whole thread still lacks surprisingly good alternatives. One is:
SortedList<string, string> x = new SortedList<string, string>();
x.Add("key1", "value1");
x.Add("key2", "value2");
x["key3"] = "value3";
foreach( KeyValuePair<string, string> kvPair in x )
Console.WriteLine($"{kvPair.Key}, {kvPair.Value}");
Why it could be argued a code smell of iterating over a dictionary (e.g. by foreach(KeyValuePair<,>) ?
A basic principle of Clean Coding:
"Express intent!"
Robert C. Martin writes in "Clean Code": "Choosing names that reveal intent". Obviously naming alone is too weak. "Express (reveal) intent with every coding decision" expresses it better.
A related principle is "Principle of least surprise" (=Principle of Least Astonishment).
Why this is related to iterating over a dictionary? Choosing a dictionary expresses the intent of choosing a data structure which was made for primarily finding data by key. Nowadays there are so much alternatives in .NET, if you want to iterate through key/value pairs that you could choose something else.
Moreover: If you iterate over something, you have to reveal something about how the items are (to be) ordered and expected to be ordered!
Although the known implementations of Dictionary sort the key collection in the order of the items added-
AFAIK, Dictionary has no assured specification about ordering (has it?).
But what are the alternatives?
TLDR:
SortedList: If your collection is not getting too large, a simple solution would be to use SortedList<,> which gives you also full indexing of key/value pairs.
Microsoft has a long article about mentioning and explaining fitting collections:
Keyed collection
To mention the most important: KeyedCollection<,> and SortedDictionary<,> .
SortedDictionary<,> is a bit faster than SortedList for only inserting if it gets large, but lacks indexing and is needed only if O(log n) for inserting is preferenced over other operations. If you really need O(1) for inserting and accept slower iterating in exchange, you have to stay with simple Dictionary<,>.
Obviously there is no data structure which is the fastest for every possible operation..
Additionally there is ImmutableSortedDictionary<,>.
And if one data structure is not exactly what you need, then derivate from Dictionary<,> or even from the new ConcurrentDictionary<,> and add explicit iteration/sorting functions!
var dictionary = new Dictionary<string, int>
{
{ "Key", 12 }
};
var aggregateObjectCollection = dictionary.Select(
entry => new AggregateObject(entry.Key, entry.Value));
Just wanted to add my 2 cent, as the most answers relate to foreach-loop.
Please, take a look at the following code:
Dictionary<String, Double> myProductPrices = new Dictionary<String, Double>();
//Add some entries to the dictionary
myProductPrices.ToList().ForEach(kvP =>
{
kvP.Value *= 1.15;
Console.Writeline(String.Format("Product '{0}' has a new price: {1} $", kvp.Key, kvP.Value));
});
Altought this adds a additional call of '.ToList()', there might be a slight performance-improvement (as pointed out here foreach vs someList.Foreach(){}),
espacially when working with large Dictionaries and running in parallel is no option / won't have an effect at all.
Also, please note that you wont be able to assign values to the 'Value' property inside a foreach-loop. On the other hand, you will be able to manipulate the 'Key' as well, possibly getting you into trouble at runtime.
When you just want to "read" Keys and Values, you might also use IEnumerable.Select().
var newProductPrices = myProductPrices.Select(kvp => new { Name = kvp.Key, Price = kvp.Value * 1.15 } );
in addition to the highest ranking posts where there is a discussion between using
foreach(KeyValuePair<string, string> entry in myDictionary)
{
// do something with entry.Value or entry.Key
}
or
foreach(var entry in myDictionary)
{
// do something with entry.Value or entry.Key
}
most complete is the following because you can see the dictionary type from the initialization, kvp is KeyValuePair
var myDictionary = new Dictionary<string, string>(x);//fill dictionary with x
foreach(var kvp in myDictionary)//iterate over dictionary
{
// do something with kvp.Value or kvp.Key
}

C# returning Dictionary references safely

I'm considering three approaches for returning references to internal Dictionary instances (C#) in regards to code safety and impact on the code readability/visually for a project I'm working on.
I've narrowed it down to the following three approaches, but am open to better suggestions. Currently I prefer #3 as the best balance of safety without extra boiler plate.
1) Use a second ReadOnlyDictionary instance to wrap internal Dictionary, only ever letting the ReadOnlyDictionary escape the class:
2) Return the Dictionary instance as an IReadOnlyDictionary, but recasting would allow it to be modified so not as safe as option #1 or #3.
3) Return Dictionary.ToImmutableDictionary() as a ImmutableDictionary when it escapes the containing class so that the returned object is an immutable view of the inner dictionary, although this will make a new copy for every call incurring a higher cost, that should be fine with small simple dictionaries (which mine are).
private readonly Dictionary<string, string> innerDictionary = new Dictionary<string, string>();
// Only required for Example #1
private readonly IReadOnlyDictionary<string, string> readonlyInnerDictionary;
public ExampleClass() {
// Only required for Example #1
readonlyInnerDictionary = new ReadOnlyDictionary<string, string>(innerDictionary);
}
public IReadOnlyDictionary<string, string> GetExampleOne() {
// Requires a second dictionary which is more boiler plate but the object being returned is truly readonly
return readonlyInnerDictionary;
}
public IReadOnlyDictionary<string, string> GetExampleTwo() {
// Requires InnerDictionary be defined as Dictionary (Not IDictionary) but doesn't require the second dictionary be defined
// which is less boiler plate, but the object returned could be re-cast to it's mutable form meaning it's not truly mutation safe.
return innerDictionary;
}
public ImmutableDictionary<string, string> GetExampleThree() {
// Truly immutable object returned, but a new instance is built for every call; fortunately all of my dictionaries are small (containing at most 9 keys)
return innerDictionary.ToImmutableDictionary();
}
Option 1 is the way to go. You can recast ReadOnlyDictionary to IDictionary, but that will throw an Exception when trying to mutate:
void CastingTest()
{
var dic1 = new Dictionary<string, string>();
dic1.Add("Key", "Value");
var dic2 = new ReadOnlyDictionary<string, string>(dic1);
var castedDic = (IDictionary<string, string>)dic2;
castedDic.Add("AnotherKey", "Another Value"); //System.NotSupportedException, Collection is read only
}
The ReadOnlyDictionary doesn't create another Dictionary. It points to the same reference of the first one, encapsulating it. So if you do:
void AddTest()
{
var dic1 = new Dictionary<string, string>();
dic1.Add("Key", "Value");
var dic2 = new ReadOnlyDictionary<string, string>(dic1);
dic1.Add("Key2", "Value2"); //Now dic2 have 2 values too.
}
Never expose your innerDictionary and you'll be fine.
Determined that the neatest, easiest and safest; but not the most performant solution is to use a ConcurrentDictionary internally which ensures thread safety (from System.Collections.Concurrent) and then to use the System.Collections.Immutable to call dictionary.ToImmutableDictionary() which creates the dictionary which escapes the inner class. The interface signature is for ImmutableDictionary<KeyType, ValueType>.
This is not the most performant solution, but in my case with dictionaries with less than 12 keys and small simple objects representing state in most cases that is not a concern.

How to make deep copy of a dictionary within Dictionary in c#? [duplicate]

This question already has answers here:
What is the best way to clone/deep copy a .NET generic Dictionary<string, T>?
(14 answers)
Closed 9 years ago.
I have four Dictionary , two are (dictionary within Dictionary), declaration shown below
Dictionary<string, Dictionary<string, string>> dict_set = new Dictionary<string, Dictionary<string, string>>();
Dictionary<string, Dictionary<string, string>> dict_Reset = new Dictionary<string, Dictionary<string, string>>();
Dictionary<string, string> set_value = new Dictionary<string, string>();
Dictionary<string, string> Reset_value = new Dictionary<string, string>();
I want to first add elements in dictionary set_vlaue and Reset_value.
once the values are added then i am adding these dictionaries to other two dictionaries as shown below.
dict_set.Add(condiName, set_value);
dict_Reset.Add(condiName, Reset_value);
set_value.Clear();
Reset_value.Clear();
the values are getting added , but after adding set_value and reset_value dictionaries , i want to clear these two dictionaries set_value and reset_value,but problem occurs that when set_value and reset_value are cleared the data from dict_set and dict_reset is also cleared..
can any one help me , to how to create deep copy of dictionaries in this case...
I do not know what you are trying to do in the workflow, but why not to reinstancing instead of cleaning?
dict_set.Clear();
to:
dict_set = new Dictionary<string, string>();
Aside of what Skeet has written in the answer pointed out by keyboardP, in most managed languages you may very easily perform deep copy by:
serializing the thing
deserializing it back
Upon deserialization, you'll usually have a complete deep clone of the original. The serializer will usually do all the ID-checking, breaking cycles, deduplicating, etc. In your case this is not necessary, but it may came handy later.
You may serialize it to XML, BinaryForm, JSON or whatever you like and have at hand. It is not that important.
Now back to your question:
This is your code, just shortened a bit:
var dict_set = new Dictionary<string, Dictionary<string, string>>();
var dict_Reset = new Dictionary<string, Dictionary<string, string>>();
var set_value = new Dictionary<string, string>();
var Reset_value = new Dictionary<string, string>();
dict_set.Add(condiName, set_value);
dict_Reset.Add(condiName, Reset_value);
set_value.Clear();
Reset_value.Clear();
You claim that:
(...) but problem occurs that when set_value and reset_value are cleared the data from dict_set and dict_reset is also cleared..
This is not true. With that code of above, it is not possible. set/reset/dict_set/dict_reset are 4 distinct objects. Calling "Clear" on "set/reset" cannot cause the others to be cleared.
Look at your code. The error is elsewhere. Not here. Something other is clearing that dict* dictionaries.
By creating new instance will solve the above issue.. if any one came across some other better solution please post..
dict_set.Add(condiName, new Dictionary<string, string>(set_value));
dict_Reset.Add(condiName, new Dictionary<string, string>(Reset_value));
set_value.Clear();
Reset_value.Clear();
I think this way the inner dictionaries in dict_set and dict_Reset will not be cleared
dict_set.Add(condiName, set_value.ToDictionary(entry => entry.Key,entry => entry.Value));
dict_Reset.Add(condiName, Reset_value.ToDictionary(entry => entry.Key,entry => entry.Value));
set_value.Clear();
Reset_value.Clear();
With the ToDictionary() method you actually create a new Dictionary object, not using the reference to tour originals dictionaries anymore, so you can safely clear them.
Adding and removing data to the set_value and Reset_value alsdo does not affect the dictionaries inside dict_set and dict_Reset
Just out of curiousity, why Reset_value with a capital S and set_value not?

Fastest of the following Mapping objects (Dictionary,Tuple,KeyvaluePair)

Currently i have a mapping setup like this
//Identifiers to save (currently)
Dictionary<string, Dictionary<string, string>> toSaveIdentifiers =
new Dictionary<string, Dictionary<string, string>>(); //
however, i want to add an extra dimension to it because i just missed out on an extra attribute to add.
I'm trying to set up some form of mapping that gets populated frequently in a program and is looked up throughout the program as well. I was wondering what is the best way to go about doing this.
//Identifiers to save (tuple)
Dictionary<Tuple<string,string>, Dictionary<string, string>> toSaveIdentifiers =
new Dictionary<Tuple<string, string>, Dictionary<string, string>>(); //
//Identifiers to save (adding another dictionary dimension)
Dictionary<string, Dictionary<string,Dictionary<string, string>>> toSaveIdentifiers =
new Dictionary<string, Dictionary<string, Dictionary<string, string>>>(); //
//Identifiers to save (adding keyvaluepair)
Dictionary<KeyValuePair<string,string>, Dictionary<string, string>> toSaveIdentifiers =
new Dictionary<KeyValuePair<string, string>, Dictionary<string, string>>(); //
When i populate it/lookup i do something like.
// check identifier map dictionary
if (dictionary.Keys.Contains(identifier))
{
if (dictionary[identifier].Keys.Contains(currency))
{
//stuff
}
else
{
//stuff
}
}
else
{
//more stuff
}
What would be the best method of doing this for lookup?
Since your identifiers all seem to be of type string, you could always just concat them all into one big string and use that as the key. Then instead of doing the nested Contains, you'd just have to do one. It'd also be more flexible as far a storing different levels of identifiers.
i.e. Given a 2 level key, it'd be
string ident = level1Identifier + "." + level2Identifier;
(using string.format() or StringBuilder would be more efficient, but this code is better for explaining)
Also consider the joining character should be something you know won't show up in any levels identifier to avoid confusion or accidently duplicates.

Delegates of types, or how to give a clumsy type a better name

In a project I'm working on, I use complicated Dictionary objects a lot. Often, there are a lot of declarations like:
var d1 = new Dictionary<string, Dictionary<int, List<string>>>();
var d2 = new Dictionary<Tuple<string, string>, List<object>>();
Between typecasts and passing parameters and what not, this gets annoying. What I'd like to do is something like this, using an imaginary keyword "typedel":
typedel ListDict = Dictionary<string, Dictionary<int, List<string>>>();
typedel PolyDict = Dictionary<Tuple<string, string>, List<object>>();
var d1 = new ListDict();
var d2 = new PolyDict();
So that I do not need to type the long Dictionary declarations every time - so what I want is something like defining shorthand abbreviations for a type name. How can I do this in the simplest way (using the fewest lines of code)?
class MyData : Dictionary<string, Dictionary<int, List<string>>>
{
}
You could also do this, but you would have to do it in every file which uses MyData, and that is probably suboptimial.
using MyData = Dictionary<string, Dictionary<int, List<string>>>;
For a "typedef" that you want to use a lot, you can just create a class that derives from the appropriate base class, as in #Ed S's answer:
class MyData : Dictionary<string, Dictionary<int, List<string>>>
{
}
However, this is not the same as what most people consider a typedef: you are introducing a new type, which has implications for things like reflection, typeof, the is operator, etc. The distinction may or may not matter to you, but it is there.
Within a single source file, however, you can use the second form of the using clause to do a real typedef:
using ListDict = Dictionary<string, Dictionary<int, List<string>>>();
using PolyDict = Dictionary<Tuple<string, string>, List<object>>();
In either case, while using a "typedef" will definitely save you typing, don't discount the benefits of seeing the types spelled out explicitly in your code. This is the same reason why articles such as this blog post recommend using List<Foo> over a custom FooCollection : List<Foo> -- with the explicit generic version you know what type of collection it is any what methods it exposes.
And, just for laughs...
static Func<T> Magic<T>(Func<T> f) { return f; }
static Func<T> Creator<T>() where T : new() { return () => new T(); }
...
var ListDict = Magic(() => new Dictionary<string, Dictionary<int, List<string>>>());
var PolyDict = Creator<Dictionary<Tuple<string, string>, List<object>>>();
var d1 = ListDict();
var d2 = PolyDict();

Categories

Resources