How do you offload a Dictionary?
-
In C#, how do you output the contents of a Dictionary class? Once you have loaded a Dictionary class with keys and values, how do I cycle through them and output the individual values in a foreach loop?
foreach (KeyValuePair<type1, type2> pair in dict)
{
Console.WriteLine("{0}, {1}",
pair.Key,
pair.Value);
}Why is common sense not common? Never argue with an idiot. They will drag you down to their level where they are an expert. Sometimes it takes a lot of work to be lazy Please stand in front of my pistol, smile and wait for the flash - JSOP 2012
-
In C#, how do you output the contents of a Dictionary class? Once you have loaded a Dictionary class with keys and values, how do I cycle through them and output the individual values in a foreach loop?
Try this
Dictionary<object, object> dummyDictionary = new Dictionary<object, object>
{
{"India","Delhi"},
{"USA","WashingtonDC"},
{"Bangaladesh","Dhaka"},
{"Pakistan","Karachi"}
};//Foreach loop construct
foreach (KeyValuePair<object, object> kvp in dummyDictionary)
{
Console.WriteLine(string.Format("Key = {0} Value = {1}", kvp.Key, kvp.Value));
}//using Linq and Foreach Extension method
var result =
(from kvp in dummyDictionary
select new
{
Key = kvp.Key
,
Value = kvp.Value
});
result.ToList().ForEach(kvp => Console.WriteLine(string.Format("Key = {0} Value = {1}", kvp.Key, kvp.Value)));Console.ReadKey();
Niladri Biswas (Code Project MVP 2012)
-
In C#, how do you output the contents of a Dictionary class? Once you have loaded a Dictionary class with keys and values, how do I cycle through them and output the individual values in a foreach loop?
There is another way as well, which can be more readable. Assuming Track is one of your classes:
Dictionary<string, Track> dict = new Dictionary<string, Track>();
foreach (Track track in DALFactory.GetAll<Track>())
{
dict.Add(track.TrackName, track);
}
...
foreach (string key in dict.Keys)
{
if (key.StartsWith("A"))
{
Track track = dict[key];
Console.WriteLine(track);
}
}Ideological Purity is no substitute for being able to stick your thumb down a pipe to stop the water
-
In C#, how do you output the contents of a Dictionary class? Once you have loaded a Dictionary class with keys and values, how do I cycle through them and output the individual values in a foreach loop?