I want to create a class that is a Custom List. So I have done
public class Set1 : List<Dictionary<string, string>>
{
public Set1() : base(List<Dictionary<string, string>>)
{
List<Dictionary<string, string>> mySet = new List<Dictionary<string, string>>()
{
new Dictionary<string, string>()
{
{"first_name","John"},
},
new Dictionary<string, string>()
{
{"last_name","Smith"},
},
};
base(mySet);
}
}
But this does not compile. What am I doing wrong please? Thanks in advance.
You can't call a base/alternate constructor from within the method in C# like you can in some other languages.
However, you don't need to call the base constructor in this case - you can just do:
public Set1()
{
this.Add(
new Dictionary<string, string>()
{
{"first_name","John"},
}
);
this.Add(
new Dictionary<string, string>()
{
{"last_name","Smith"},
}
);
}
If you really want to call the base constructor, though, you'll have to inline the list creation in the declaration:
public Set1()
: base( new List<Dictionary<string, string>>
{
new Dictionary<string, string>()
{
{"first_name","John"},
},
new Dictionary<string, string>()
{
{"last_name","Smith"},
}
}
)
{
// nothing more to do here
}
but that creates a list, only to have the constructor copy the items into the list, increasing your memory usage for a short time.
Here is the code you're looking for
new Dictionary<string, string>() {
{"first_name","John"}, {"last_name","Smith"},
}.
You don't have any need to inherit from List here. What you wanted was an instance of some collection. A class is a general template for data and behaviour, not something you define to hold the specific information for John.
Even better, create a class for the apprioriate thing (a person), and create an instance of a List<Person>
public class Person
{
public string Forename {get;set;}
public string Surname {get;set;}
}
///
var people = new List<Person>() { new Person("John", "Smith") };
Related
Can I not write values into my nested dictionary directly?
It would be nice if I could access it like this:
public Dictionary<string, Dictionary<string, Dictionary<string, int>>> planets =
new Dictionary<string, Dictionary<string, Dictionary<string, int>>>();
planets[Planet.CharacterId]["MetalMine"]["Level"] = 0;
But I'm getting:
KeyNotFoundException: The given key was not present in the dictionary.
Does this mean I got to insert my Keys after each other?
Does this mean I got to insert my Keys after each other?
Yes, you need to initialize each in order:
planets[Planet.CharacterId] = new Dictionary<string, Dictionary<string, int>>();
planets[Planet.CharacterId]["MetalMine"] = new Dictionary<string, int>();
planets[Planet.CharacterId]["MetalMine"]["Level"] = 0;
You could use collection initializer syntax here, but that won't make stuff much more readable nor maintainable.
Instead of a dictionary of dicionaries of dictionaries you seem to be better off using a class:
public class Planet
{
public List<Mine> Mines { get; set; }
}
public class Mine
{
public string Type { get; set; }
public int Level { get; set; }
}
var planets = new Dictionary<string, Planet>();
planets[Planet.CharacterId] = new Planet
{
Mines = new List<Mine>
{
new Mine
{
Type = "Metal",
Level = 0
}
};
}
It's may be helpful or Nested dictionary alternative.
Create Sample.cs script and test it.
public Dictionary<string,Tuple<string,string,string,int>> _planets = new Dictionary<string, Tuple<string,string, string, int>>();
void Start()
{
string myKey = string.Concat("1","MetalMine","Level");
if(!_planets.ContainsKey(myKey))
{
_planets.Add(myKey,Tuple.Create("1","MetalMine","Level",0));
}
Debug.Log("_planets mykey "+myKey+" ==> "+_planets[myKey].Item4);
}
Re-written everything exactly as my program has it:
class DictionaryInitializer
{
public class DictionarySetup
{
public string theDescription { get; set; }
public string theClass { get; set; }
}
public class DictionaryInit
{
//IS_Revenues data
public Dictionary<int, DictionarySetup> accountRevenue = new Dictionary<int, DictionarySetup>()
{
{ 400000, new DictionarySetup {theDescription="Call", theClass="Revenues"}},
{ 400001, new DictionarySetup {theDescription="Bill", theClass="Revenues"}},
{ 495003, new DictionarySetup {theDescription="Revenue", theClass="Revenues"}}
};
public Dictionary<int, DictionarySetup> accountExpenses = new Dictionary<int, DictionarySetup>()
{
{790130, new DictionarySetup { theDescription="Currency Hedge", theClass="Other income/expense"}},
{805520, new DictionarySetup { theDescription="Int Income", theClass="Other income/expense"}}
};
}
On my mainform:
DictionaryInit theDictionary;
btnClick() {
theDictionary = new DictionaryInit();
//Some code to loop through a datagridview
//Somemore Code
foreach (var item in theDictionary.accountRevenue)
{
int theKey = item.Key;
if (theKey == keyCode)
{
DictionarySetup theValues = item.Value;
DGVMain.Rows[rowindex].Cells[3].Value = theValues.theDescription;
DGVMain.Rows[rowindex].Cells[11].Value = theValues.theClass;
DGVMain.Rows[rowindex].Cells[12].Value = "Sale of Services";
Recording(rowindex);
}
}
}
Current work in progress:
DictionarySetup theValue;
if (theDictionary.accountExpenses.TryGetValue(keyCode,out theValue.theDescription) //[5]-> Account Type
{
//Some code to write dictionary data to the data grid view.
I'm working on making the TryGetValue and Contains(value) dictionary functions to work for now.
My current error messages are as follows:
"a property or indexer may not be passed as an out or ref parameter" when attempting the trygetvalue
and finally when trying the extension method i'm trying to create:
"Inconsistent accessibility, Dictionary<int, DictionaryInitializer.DictionarySetup> is less accessible than the method DictionaryUse<int, DictionaryInitializer.DictionarySetup>"
You have to make your field public....
Dictionary<int, DictionarySetup> accountRevenue
should be
public Dictionary<int, DictionarySetup> accountRevenue
if you want to refer to it from outside the class..
This part seems to also be missing a variable name;
public void DictionaryUse (int code, int key, Dictionary)
should be
public void DictionaryUse (int code, int key, Dictionary<int, DictionarySetup> theDictionary)
But I agree with the other comments, you seem to be re-inventing the wheel, just use the existing Dictionary utility methods
I am trying to automap a dictionary to another without replacing existing values with null but just update them with the new ones if necessary. However i can't get it to work anyway.
Code :
class Klass
{
public Dictionary<string, string[]> Dictionary = new Dictionary<string, string[]>();
}
class Main
{
private Klass ex1 = new Klass();
public Main()
{
Mapper.CreateMap<Klass, Klass>().ForAllMembers(opt => opt.Condition(srs => !srs.IsSourceValueNull));
TestRun("1");
TestRun("2");
TestRun("3");
//EVERY CALL REPLACES THE OTHER HERE IDK WHY [OTHER MAPPER VALUES I MEAN]
}
public void TestRun(string text)
{
var ex2 = new Klass();
ex2.Dictionary = new Dictionary<string, string[]>
{
{text, new []{"1", "2... etc as provided"}}
};
Mapper.Map(ex2, ex1);
}
}
It seems that Dictionary<,> performance is affected by the size of the item being stored (which seems bizarre).
Here's my simple class:
public class MyObject
{
public Guid Key { get; set; }
}
And two simple tests:
private long _Iterations = 1000000;
[TestMethod]
public void ShouldTestDefaultConstructorPerformance()
{
for (var i = 0; i < _Iterations; i++)
{
var obj = new MyObject() { Key = Guid.NewGuid() };
}
}
[TestMethod]
public void ShouldTestDefaultGuidDictionaryPerformance()
{
var dict = new Dictionary<Guid, MyObject>();
for (var i = 0; i < _Iterations; i++)
{
var obj = new MyObject() { Key = Guid.NewGuid() };
dict.Add(obj.Key, obj);
}
}
Initially I get the following timings:
ShouldTestDefaultConstructorPerformance : 00:00:00.580
ShouldTestDefaultGuidDictionaryPerformance : 00:00:01.238
Now, I'll change MyObject class:
public class MyObject
{
public Guid Key { get; set; }
private Dictionary<string, string> _Property0 = new Dictionary<string, string>();
private Dictionary<string, string> _Property1 = new Dictionary<string, string>();
private Dictionary<string, string> _Property2 = new Dictionary<string, string>();
private Dictionary<string, string> _Property3 = new Dictionary<string, string>();
private Dictionary<string, string> _Property4 = new Dictionary<string, string>();
private Dictionary<string, string> _Property5 = new Dictionary<string, string>();
private Dictionary<string, string> _Property6 = new Dictionary<string, string>();
private Dictionary<string, string> _Property7 = new Dictionary<string, string>();
private Dictionary<string, string> _Property8 = new Dictionary<string, string>();
private Dictionary<string, string> _Property9 = new Dictionary<string, string>();
}
And run the tests again:
ShouldTestDefaultConstructorPerformance : 00:00:01.333
ShouldTestDefaultGuidDictionaryPerformance : 00:00:07.556
In the second test, the object construction takes 1.72x longer, but adding to the Dictionary takes 6.11x longer. I expected the tests to take longer, but why does the Dictionary take so much longer to add larger objects?
I think people need to read questions more carefully instead of rushing to post an answer. If you look at his sample code carefully (BOTH tests), the difference between having a MyObject with a Guid and MyObject with a Guid and 10 Dict's is under a second (object construction) for his loop. However the add dictionary accounts for at least 5 more seconds.
I think my answer would be: use a profiler and work out which bit is actually taking longer.
That'd probably highlight the instantiation. Maybe :)
I would think that var obj = new MyObject() { Key = Guid.NewGuid() }; this line actually takes much longer and not Add() of dictionary. Did you make measuring inside methods provided?
Each object you add to the dictionary is given a special unique identifier to speed up its searching and retrieval in memory. This special unique identifier (called a hash) is computed by analysing the entire content of the object. The larger the object, the slower it will be to compute the hash.
If you are interested in the fine details of how it works, check out this example from a university course: http://www.ccs.neu.edu/home/sbratus/com1101/hash-dict.html
Can someone point me out to some C# code examples or provide some code, where a Dictionary has been used as a property for a Class.
The examples I have seen so far don't cover all the aspects viz how to declare the dictionary as property, add, remove, and retrieve the elements from the dictionary.
Here's a quick example
class Example {
private Dictionary<int,string> _map;
public Dictionary<int,string> Map { get { return _map; } }
public Example() { _map = new Dictionary<int,string>(); }
}
Some use cases
var e = new Example();
e.Map[42] = "The Answer";
sample code:
public class MyClass
{
public MyClass()
{
TheDictionary = new Dictionary<int, string>();
}
// private setter so no-one can change the dictionary itself
// so create it in the constructor
public IDictionary<int, string> TheDictionary { get; private set; }
}
sample usage:
MyClass mc = new MyClass();
mc.TheDictionary.Add(1, "one");
mc.TheDictionary.Add(2, "two");
mc.TheDictionary.Add(3, "three");
Console.WriteLine(mc.TheDictionary[2]);
EDIT
When you use C# version 6 or later, you can also use this:
public class MyClass
{
// you don't need a constructor for this feature
// no (public) setter so no-one can change the dictionary itself
// it is set when creating a new instance of MyClass
public IDictionary<int, string> TheDictionary { get; } = new Dictionary<int, string>();
}
You could also look into indexers. (official MSDN documentation here)
class MyClass
{
private Dictionary<string, string> data = new Dictionary<string, string>();
public MyClass()
{
data.Add("Turing, Alan", "Alan Mathison Turing, OBE, FRS (pronounced /ˈtjʊ(ə)rɪŋ/) (23 June, 1912 – 7 June, 1954) was a British mathematician, logician, cryptanalyst and computer scientist.")
//Courtesy of [Wikipedia][3]. Used without permission
}
public string this [string index]
{
get
{
return data[index];
}
}
}
Then, once you have populated the dictionary internally, you can access it's information by going
MyClass myExample = new MyClass();
string turingBio = myExample["Turing, Alan"];
EDIT
Obviously, this has to be used carefully, because MyClass is NOT a dictionary, and you cannot use any dictionary methods on it unless you implement them for the wrapper class. But indexers are a great tool in certain situations.
In order to ensure the encapsulation is correct and the dictionary cannot be updated outside the class using Add or the form ExampleDictionary[1]= "test", use IReadOnlyDictionary.
public class Example
{
private Dictionary<int, string> exampleDictionary;
public Example()
{
exampleDictionary = new Dictionary<int, string>();
}
public IReadOnlyDictionary<int, string> ExampleDictionary
{
get { return (IReadOnlyDictionary<int, string>)exampleDictionary; }
}
}
The following code will not work, which is not the case if IDictionary is used:
var example = new Example();
example.ExampleDictionary[1] = test;
Another example of using a dictionary as a static property with only the get accessor:
private static Dictionary <string, string> dict = new Dictionary <string,string>(){
{"Design Matrix", "Design Case"},
{"N/A", "Other"}
};
public static Dictionary <string, string> Dict
{
get { return dict}
}
This structure can be used to replace values.
An example...
public class Example
{
public Dictionary<Int32, String> DictionaryProperty
{
get; set;
}
public Example()
{
DictionaryProperty = new Dictionary<int, string>();
}
}
public class MainForm
{
public MainForm()
{
Example e = new Example();
e.DictionaryProperty.Add(1, "Hello");
e.DictionaryProperty.Remove(1);
}
}
Since .net 4.6 you can also define a Dictionary like this:
private Dictionary<string,int> Values => new Dictionary<string, int>()
{
{ "Value_1", 1},
{ "Value_2", 2},
{ "Value_3", 3},
};
It's called Expression-bodied members!
You mean like a property bag ?
http://www.codeproject.com/KB/recipes/propertybag.aspx