How to access Dictionary from other Class's function in C#? - c#

I have create a Class named "EngDictionary". and Then i define a dictionary in a function
e.g:
public void Dict()
{
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("Classifieds", "Kleinanzeigen");
//d.Add("windows", 5);
}
Now i want to access above defined dictionary from my main class for retrieving the keys and values of my Dictionary. Please Suggest me some code. I am using Visual C# 2008 Express Edition, Win Application

Declare Dictionary as class property.
public class Dict {
private Dictionary<string, string> dict;
public SomeDictionary { get dict; set dict = value; }
public Dict() {
dict = new Dictionary<string, string>();
dict.Add("Classifieds", "Kleinanzeigen");
}
}
In other class:
Dict d = new Dict();
string test = d.SomeDictionary["Classifieds"];
Console.WriteLine(test);

return the dictionary from the method.
public Dictionary<string, string> Dict() {.... ; return d;}
In your main class.
EngDictionary dict = new EngDictionary();
Dictionary<string, string> dictionary = dict.Dict();

You can declare Dictionary<string, string> d as a member variable of your class , and initialize this object in the class constructor.You can have a getter method to get the dictionary in other classes.
public class EngDictionary
{
Dictionary<string, string> dictionary;
public void EngDictionary()
{
dictionary = new Dictionary<string, string>();
dictionary.Add("Classifieds", "Kleinanzeigen");
....
}
public Dictionary<string, string> getDictionary()
{
return this.dictionary;
}
}

I have a class
public class Dict
{
public Dictionary<string, string> SomeDictionary { get; } = new Dictionary<string, string>()
{
{ "Classifieds", "Kleinanzeigen" }
};
}
then in any other class
Dict Dic = new Dict();
foreach (var item in Dic.SomeDictionary)
{
Console.WriteLine(item.Key);
Console.WriteLine(item.Value);
}

Related

C# Assign static dictionary to filtered version of other dictionary in static class

I have a class, with some global and constant dictionaries. Like:
public static class Constants
{
public static Dictionary<string, MyObject> MyDictionary= new Dictionary<string, MyObject>()
{
{"first", new MyObject()},
{"second", new MyObject()},
};
}
Lets say I would like another dictionary, to be like that only with some added and removed elements. Is there a way to achieve that, within the static class? I imagine something like:
public static Dictionary<string, MyObject> MyOtherDictionary = MyDictionary.Remove("second").Add("Third", new MyObject())
But I know that does not work, so is there any way I can achieve this?
No, that doesnt work in this way for two reasons:
Remove returns a bool, you can't use Add on a bool
even if you make it compile, you don't want to modify the other dictionary but you want to create a new dictionary which contains similar items, you can use the constructor:
public static Dictionary<string, MyObject> MyOtherDictionary;
// ...
static Constants
{
MyOtherDictionary = new Dictionary<string, MyObject>(MyDictionary);
MyOtherDictionary.Remove("second");
MyOtherDictionary.Add("Third", new MyObject());
}
You could do it using properties instead
public static class Constants
{
public static Dictionary<string, MyObject> myDictionary
{
get
{
return new Dictionary<string, MyObject>()
{
{ "first", new MyObject()},
{ "second", new MyObject()},
};
}
}
static Dictionary<string, MyObject> _myOtherDictionary;
public static Dictionary<string, MyObject> myOtherDictionary
{
get
{
_myOtherDictionary = myDictionary;
_myOtherDictionary.Remove("first");
_myOtherDictionary.Add("third", new MyObject());
return _myOtherDictionary;
}
}
}

get access of dictionary elements in to another class

I have a class with two dictionaries .and i want access these dictionary in other class.these is my class.
{
public class DictionaryLines
{
private Dictionary<string, string> line1dictionary;
private Dictionary<string, string> line2dictionary;
public DictionaryLines()
{
line1dictionary = new Dictionary<string, string>();
line2dictionary = new Dictionary<string, string>();
line1dictionary.Add("A1", "Miyapur");
line1dictionary.Add("A2", "JNTU College");
line1dictionary.Add("A3", "KPHB Colony");
line1dictionary.Add("A4", "Kukatpally");
line1dictionary.Add("A5", "Balanagar");
line1dictionary.Add("A6", "Moosapeta");
line1dictionary.Add("A7", "Bharath nagar");
line1dictionary.Add("A8", "Erragadda");
line2dictionary.Add("B1", "JBS");
line2dictionary.Add("X3", "Parade Grounds");
line2dictionary.Add("B3", "Secundrabad");
line2dictionary.Add("B4", "Gandhi Hospital");
}
}
how i can call this dictionary into other class..thank you
Adding two public properties which return the fields would be the easiest way.
{
public class DictionaryLines
{
private Dictionary<string, string> line1dictionary;
private Dictionary<string, string> line2dictionary;
public Dictionary<string, string> Line1Dictionary { get { return line1dictionary; } }
public Dictionary<string, string> Line2Dictionary { get { return line2dictionary; } }
public DictionaryLines()
{
line1dictionary = new Dictionary<string, string>();
line2dictionary = new Dictionary<string, string>();
line1dictionary.Add("A1", "Miyapur");
line1dictionary.Add("A2", "JNTU College");
line1dictionary.Add("A3", "KPHB Colony");
line1dictionary.Add("A4", "Kukatpally");
line1dictionary.Add("A5", "Balanagar");
line1dictionary.Add("A6", "Moosapeta");
line1dictionary.Add("A7", "Bharath nagar");
line1dictionary.Add("A8", "Erragadda");
line2dictionary.Add("B1", "JBS");
line2dictionary.Add("X3", "Parade Grounds");
line2dictionary.Add("B3", "Secundrabad");
line2dictionary.Add("B4", "Gandhi Hospital");
}
}
//Change the scope private to public like
public Dictionary<string, string> line1dictionary;
public Dictionary<string, string> line2dictionary;
You can access private members in another class using reflection.
like this:
public class DictionaryLines
{
private Dictionary<string, string> line1dictionary;
private Dictionary<string, string> line2dictionary;
public DictionaryLines()
{
line1dictionary = new Dictionary<string, string>();
line2dictionary = new Dictionary<string, string>();
line1dictionary.Add("A1", "Miyapur");
line1dictionary.Add("A2", "JNTU College");
line1dictionary.Add("A3", "KPHB Colony");
line1dictionary.Add("A4", "Kukatpally");
line1dictionary.Add("A5", "Balanagar");
line1dictionary.Add("A6", "Moosapeta");
line1dictionary.Add("A7", "Bharath nagar");
line1dictionary.Add("A8", "Erragadda");
line2dictionary.Add("B1", "JBS");
line2dictionary.Add("X3", "Parade Grounds");
line2dictionary.Add("B3", "Secundrabad");
line2dictionary.Add("B4", "Gandhi Hospital");
}
}
class Program
{
static void Main(string[] args)
{
var cls = new DictionaryLines().GetType();
var attrs = cls.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
foreach(var k in attrs)
{
Console.WriteLine("----------------------"+k.Name+"------------------------------");
foreach (var j in (Dictionary<string, string>)k.GetValue(new DictionaryLines()))
{
Console.WriteLine("Key = "+j.Key +" & Value = "+j.Value);
}
}
Console.Read();
}
}

How can I initialize a global nested Dictionary globally?

I have my Dictionary declared like this:
private static Dictionary<string, Dictionary<string, string>> myDictionary;
I want to initialize it globally. The closest I have come initializes the outer Dictionary, but still leaves me with a null reference to the inner Dictionary:
private static Dictionary<string, Dictionary<string, string>> myDictionary
= new Dictionary<string, Dictionary<string, string>>();
I need to avoid initializing it in a method, because I don't want to force the user to call a method before being able to use my class. The user only has access to static methods. I could create a singleton when they call one of the methods, but that's dirty.
How can I declare both dictionaries globally? Something along the lines of one of these (although neither compile):
private static Dictionary<string, Dictionary<string, string>> myDictionary
= new Dictionary<string, new Dictionary<string, string>>();
or
private static Dictionary<string, string> inner = new Dictionary<string, string>();
private static Dictionary<string, Dictionary<string, string>> myDictionary
= new Dictionary<string, inner>();
Use the static constructor like this (assuming that the myDictionary variable is in a class called MyClass) :
public class MyClass
{
private static Dictionary<string, Dictionary<string, string>> myDictionary;
static MyClass()
{
//Initialize static members here
myDictionary = new Dictionary<string, Dictionary<string, string>>();
myDictionary.Add("mykey", new Dictionary<string, string>());
...
}
}
The framework will make sure that the static constructor is automatically executed before you access any member of the class.
You can initialize it inline without doing it in a method by following the {} collection initialization syntax:
private static Dictionary<string, Dictionary<string, string>> = new Dictionary<string, Dictionary<string, string>> {
{ "first"
, new Dictionary<string, string> {
{"A", "one"}
, {"B", "two"}
}
}
, { "second"
, new Dictionary<string, string> {
{"Y", "twenty five"}
, {"Z", "twenty six"}
}
}
}

Static dictionary call "System.TypeInitializationException"

I have a static class to hold a dictionary and 2 get methods to access it
Here is my class:
public static class ConfiguraCuadros
{
public static Dictionary<string,Dictionary<string,Dictionary<string,Dictionary<string,string>>>> GetDictionary()
{
// Try to get the result in the static Dictionary
return _configcuadros;
}
public static Dictionary<string, Dictionary<string, Dictionary<string, string>>> GetHoja(string key)
{
// Try to get the result in the static Dictionary
Dictionary<string, Dictionary<string, Dictionary<string, string>>> result = new Dictionary<string, Dictionary<string, Dictionary<string, string>>>();
if (_configcuadros.TryGetValue(key, out result))
{
return result;
}
else
{
return null;
}
}
public static readonly Dictionary<string, Dictionary<string, Dictionary<string, Dictionary<string, string>>>> _configcuadros = new Dictionary<string, Dictionary<string, Dictionary<string, Dictionary<string, string>>>>
{
{ "Formato01", //this is just a hint, the dictionary is much more extensive
new Dictionary<string, Dictionary<string, Dictionary<string, string>>>
{
{
"F01C01A",
new Dictionary<string, Dictionary<string, string>>
{
{
"X",
new Dictionary<string, string>
{
{ "key1" , "value1" },
{ "key2" , "value2" },
{ "key3" , "value3" },
}
},
}
},
}
},
}
}`
When I use the getter method,
ConfiguraCuadros.GetDictionary();
It throws an exception:
A first chance exception of type 'System.ArgumentException' occurred in mscorlib.dll
'ConfiguraCuadros.GetDictionary()' threw an exception of type 'System.TypeInitializationException'
base: {"The type initializer for 'beDGRAIC.ConfiguraCuadros' threw an exception."}
TypeName: "beDGRAIC.ConfiguraCuadros"
or
'ConfiguraCuadros.GetHoja("Formato01")' threw an exception of type 'System.TypeInitializationException'
base: {"The type initializer for 'beDGRAIC.ConfiguraCuadros' threw an exception."}
TypeName: "beDGRAIC.ConfiguraCuadros"
As you can see, my intention is to have a static dictionary. I think the problem is in the dictionary declaration ... but I can't see where...
Just in case, "beDGRAIC" is my namespace.
Thanks for your help!
Your code works (almost) as is for me.
I just added a missing semi-colon to get it to compile but can then call ConfiguraCuadros.GetDictionary(); without any exception.
Here is the code back with that missing semicolon:
public static class ConfiguraCuadros
{
public static Dictionary<string, Dictionary<string, Dictionary<string, Dictionary<string, string>>>> GetDictionary()
{
// Try to get the result in the static Dictionary
return _configcuadros;
}
public static Dictionary<string, Dictionary<string, Dictionary<string, string>>> GetHoja(string key)
{
// Try to get the result in the static Dictionary
Dictionary<string, Dictionary<string, Dictionary<string, string>>> result = new Dictionary<string, Dictionary<string, Dictionary<string, string>>>();
if (_configcuadros.TryGetValue(key, out result))
{
return result;
}
else
{
return null;
}
}
public static readonly Dictionary<string, Dictionary<string, Dictionary<string, Dictionary<string, string>>>> _configcuadros = new Dictionary<string, Dictionary<string, Dictionary<string, Dictionary<string, string>>>>
{
{ "Formato01", //this is just a hint, the dictionary is much more extensive
new Dictionary<string, Dictionary<string, Dictionary<string, string>>>
{
{
"F01C01A",
new Dictionary<string, Dictionary<string, string>>
{
{
"X",
new Dictionary<string, string>
{
{ "key1" , "value1" },
{ "key2" , "value2" },
{ "key3" , "value3" },
}
},
}
}
}
}
};
}
[UPDATE]
I do agree with the comments above about checking out the InnerException as a general rule for a type initialisation exception and, particularly, about the unfriendly nature of the datatype!

Serializing a class containing a Dictionary of Dictionay

I have defined a class which contains only one member of type dictionary of dictionary. I want to serialize it to JSON format and hence using JavaScriptSerializer.
[Serializable]
class X
{
private readonly Dictionary<string, Dictionary<string, string>> dic;
public X()
{
dic = new Dictionary<string, Dictionary<string, string>>();
}
public void Add()
{
this.dic.Add("x", new Dictionary<string, string>() { { "a", "b" } });
}
}
class Program
{
static void Main(string[] args)
{
var x = new X();
x.Add();
string msg = new JavaScriptSerializer(new SimpleTypeResolver()).Serialize(x);
var y = new JavaScriptSerializer(new SimpleTypeResolver()).Deserialize<X>(msg);
}
}
Now, the above code run successful without any error/exception but the results are not as excepted. The serialized string of class X in the above code is
{"__type":"Testing.X, Testing, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"}
Can anybody tell me whats the problem in the above code and what I'm missing? Also, if in the above class, I change the inner dictionary type to Dictionary<string, IEntity> then what all I have to do to serialize it.
JavaScriptSerializer is designed to only pull public properties by default. Once you expose the field through a getter or setter you should be able to serialize this data.
[Serializable]
class X
{
private readonly Dictionary<string, Dictionary<string, string>> dic;
public X()
{
dic = new Dictionary<string, Dictionary<string, string>>();
}
public void Add()
{
this.dic.Add("x", new Dictionary<string, string>() { { "a", "b" } });
}
//Property exposing private field 'dic'.
public Dictionary<string, Dictionary<string, string>> Dictionary
{
get
{
return dic;
}
}
}
class Program
{
static void Main(string[] args)
{
var x = new X();
x.Add();
string msg = new JavaScriptSerializer(new SimpleTypeResolver()).Serialize(x);
var y = new JavaScriptSerializer(new SimpleTypeResolver()).Deserialize<X>(msg);
}
}
In this case, the string contains the following output (look to the very end):
{"__type":"ConsoleApplication1.X, ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null","Dictionary":{"x":{"a":"b"}}}

Categories

Resources