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();
}
}
Related
I'm trying to learn and practice OOP principles and I need some help with an example to get me over the hump. I have the following code:
using System.Collections.Generic;
namespace Test
{
class Program
{
static void Main()
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("cat", "one");
dictionary.Add("dog", "two");
dictionary.Add("llama", "three");
dictionary.Add("iguana", "four");
var test1 = GetKVP(dictionary, "llama");
var test2 = GetValue(dictionary, "llama");
var test3 = GetPosition(dictionary, "llama");
}
static KeyValuePair<string, string> GetKVP(Dictionary<string, string> dict, string key_to_find)
{
foreach (KeyValuePair<string, string> kvp in dict)
{
if (kvp.Key == key_to_find)
{return kvp;}
}
return new KeyValuePair<string, string>();
}
static string GetValue(Dictionary<string, string> dict, string key_to_find)
{
foreach (KeyValuePair<string, string> kvp in dict)
{
if (kvp.Key == key_to_find)
{return kvp.Value;}
}
return string.Empty;
}
static int GetPosition(Dictionary<string, string> dict, string key_to_find)
{
int counter = 0;
foreach (KeyValuePair<string, string> kvp in dict)
{
if (kvp.Key == key_to_find)
{return counter;}
counter += 1;
}
return -1;
}
}
}
What I'm trying to do is consolidate the code set so that I can have a single method which returns a different data type without duplicating code. Please don't comment on the fact that there are several more efficient ways to search a dictionary, I'm aware that this is not ideal.. I simply mocked up some data and methods to use as an example. For the life of me, I can't really visualize how to implement something like that.
You could try doing this, but I don't think it helps too much:
static R GetResult<R>(Dictionary<string, string> dict, string key_to_find, Func<KeyValuePair<string, string>, R> selector, R otherwise)
{
return dict.Where(kvp => kvp.Key == key_to_find).Select(kvp => selector(kvp)).DefaultIfEmpty(otherwise).First();
}
static KeyValuePair<string, string> GetKVP(Dictionary<string, string> dict, string key_to_find)
{
return GetResult(dict, key_to_find, kvp => kvp, new KeyValuePair<string, string>());
}
static string GetValue(Dictionary<string, string> dict, string key_to_find)
{
return GetResult(dict, key_to_find, kvp => kvp.Value, String.Empty);
}
static int GetPosition(Dictionary<string, string> dict, string key_to_find)
{
return dict.Where(kvp => kvp.Key == key_to_find).Select((kvp, n) => n).DefaultIfEmpty(-1).First();
}
In .net everthing is based on Object, so just return Object and then object could be anything just as you want
here is a sample based on your code
using System.Collections.Generic;
namespace Test
{
class Program
{
static void Main()
{
Dictionary<string, Object> dictionary = new Dictionary<string, string>();
dictionary.Add("cat", "one");
dictionary.Add("dog", "two");
dictionary.Add("llama", "three");
dictionary.Add("iguana", "four");
var test1 = GetWhatEver(dictionary, "llama");
var test2 = GetWhatEver(dictionary, "llama");
var test3 = GetWhatEver(dictionary, "llama");
}
static Object GetWhatEver(Dictionary<string, Object> dict, string key_to_find)
{
foreach (var kvp in dict)
{
if (kvp.Key == key_to_find)
{return kvp.Value;}
}
return null;
}
}
}
I have an ASP.NET MVC app. I need a Dictionary<string, string> that is available throughout the entire app at runtime. My question is, where is the best place/way to define this Dictionary? I assume I need to do it in the Global.asax file. Yet, I'm not sure.
Create a utility class and use Lazy to pospone intialization until the first hit:
public static class InfoHelper
{
private static Lazy<ConcurrentDictionary<string, string>> infoBuilder
= new Lazy<ConcurrentDictionary<string, string>>( () => SomeCreationMethod() );
public static ConcurrentDictionary<string, string> Info
{
get
{
return infoBuilder.Value;
}
}
Or, using HttpContext.Cache:
public static class InfoHelper
{
public static ConcurrentDictionary<string, string> Info
{
get
{
ConcurrentDictionary<string, string> d
= HttpContext.Current.Cache["someId"] as ConcurrentDictionary<string, string>;
if (d == null)
{
d = HttpContext.Current.Cache["someId"] = SomeCreationMethod();
}
return d;
}
}
Or, when setting this from an external class:
public static class InfoHelper
{
public static ConcurrentDictionary<string, string> Info
{
get
{
return HttpContext.Current.Cache["someId"] as ConcurrentDictionary<string, string>;
}
set
{
HttpContext.Current.Cache["someId"] = value;
}
}
Then set it from another class:
InfoHelper.Info = ...;
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!
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"}}}
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);
}