I have a question about how to get values from my Dictionary<string, List<object>>, I tried all examples which I found in google, but still can't get something readable value.....
so, here is the code:
List<object> listValues = new List<object>();
listValues.Add(risk);
listValues.Add(validFrom);
listValues.Add(effectiveDate);
Dictionary<string, List<object>> dic = new Dictionary<string, List<object>>();
dic.Add(nameOfInsuredObject, listValues);
foreach (object value in dic.Values)
{
System.Console.WriteLine(value);
}
I can get key from dictionary, but with getting value I am stucked now....
And here is the result of this code:
Key => testInsObj
Values => System.Collections.Generic.List`1[System.Object]
So can anyone help me with it? I am new in C#, so maybe this is easy questions for others....
It seems you are looking for writing values of the list this way:
foreach (var value in dic.Values)
{
value.ForEach(Console.WriteLine);
}
In fact each element of the Dictionary is <string, List<Object>>. So, when you want to write Value part of the pair to console, you need a for loop to write each element of the List<object>.
It is confusing for new C# users, how to access the dictionary.
When you do a foreach on the dictionary, you get a KeyValuePair<TKey, TValue>. Now this KeyValuePair<TKey, TValue>, has 2 properties KeyValuePair.Key and KeyValuePair.Value, representing the Key and Value stored in the dictionary.
Also, the Value in your case is a List<T>, which means doing a Console.WriteLine on it will not print the whole List<T> (as some people expect), but just some reference string. You will have to "loop" over the list to print individual elements. Needless to say, depending on what you want to do with the element in the List<T>, you can use LINQ or some other common C# idiom.
foreach (var value in dic) {
Console.WriteLine(value.Key);
foreach (var item in value.Value)
Console.WriteLine(item);
}
Related
I've been reading a lot of documentation on how to iterate a Dictionary with a foreach, but I don't quite understand how I can go through the levels it has. For example:
I have "params" Dictionary, I add string and object values to it, with .Add(), and to one of them I add a level called "item".
From what I understand, with the Foreach(KeyValueaPair<>) it is to iterate through the Dictionary. Do I need to use another foreach(KeyValuePair<>) to be able to loop through the second level?
For example, I want "param" to get the value of the element that Posnr brings
IDictionary<string, object> params = new Dictionary<string, object>();
params.Add("Customerid", zwCustomer.Customerid);
params.Add("PedidoCli", zwCustomer.PedidoCli);
params.Add("PedidoSap", zwCustomer.PedidoSap);
params.Add("TFacturaMat", new Dictionary<string, object>()
{
{
"item", new Dictionary<string, object>()
{
{"Vbeln", zfacturaMats.Vbeln},
{"Posnr", zfacturaMats.Posnr},
{"Matnr", zfacturaMats.Matnr},
}
},
});
foreach(KeyValuePair<string, object> item in parametros)
{
param = $"{item.Key} : {item.Value}";
}
No, you can do that directly. The Dictionary<TKey, TValue> class of the .NET library already does all that magic for you.
With the foreach loop
foreach(KeyValuePair<string, object> item in params)
{
Console.WriteLine($"{item.Key} : {item.Value}");
}
you already iterate trough all the elements of your dictionary. From an usage point of view this works exactly the same as if params was a List (except that there's no guaranteed order).
If you want a particular element, you have multiple possibilities, but in the easiest case you can just get an element by var myValue = params["PosNr"]. Alternatively you can use the TryGetValue() method to test whether a certain key is present.
So bottom line: It's interesting to know how a dictionary works internally, but when you use the .NET libraries, you don't have to care about that. Iterating and accessing works just out of the box.
This question already has answers here:
How to iterate over a dictionary?
(29 answers)
Closed 8 years ago.
I have a:
var selectedDates = new Dictionary<string, string>();
selectedDates.Add("2014-06-21", DateTime.Now.ToLongDateString());
selectedDates.Add("2014-07-21", DateTime.Now.AddDays(5).ToLongDateString());
selectedDates.Add("2014-08-21", DateTime.Now.AddDays(9).ToLongDateString());
selectedDates.Add("2014-09-21", DateTime.Now.AddDays(14).ToLongDateString());
How can I loop trough items without knowing the key?
For example I want to get the value of the item[0]
If I do:
var item = selectedDates[0].value; // I get an error
How can I loop trough items without knowing the key?
For example I want to get the value of the item[0]
You want to treat the dictionary as (ordered) collection similar to a list or array and get the first item in it?
You can because a Dictionary<string, string> is an IEnumerable<KeyValuePair<string, string>> implicitly. Just use First or FirstOrDefault:
string valueAtFirstPosition = selectedDates.First().Value;
However, note that a dictionary is not meant to be used as as an ordered collection. It is a collection which can be used to fast-lookup a value by a key. But you can enumerate it anyway.
foreach(KeyValuePair<string, string>keyVal in selectedDates)
{
Console.WriteLine("Key: {0} Value: {1}", keyVal.Key, keyVal.Value);
}
You should simply not rely on that order. I think in the current implementation the order is stable as long as you don't delete items. Read
Read: Why is a Dictionary “not ordered”?
try this
foreach (string key in selectedDates.Keys)
{
var item = selectedDates[key];
}
It's simple, loop trough it with a foreach or to get a specific index do:
var date = selectedDates.ElementAt(0).Value;
Let me put together two things for you. Firstly, you can loop or use LINQ to access elements, just as you could do it in a list as well:
var dict = new Dictionary<string, string>();
// loop
foreach (var item in dict)
{
var key = item.Key;
var value = item.Value;
}
// "first" (see below)
var firstItem = dict.First();
However, be aware that what you're referring to as the first item can be pretty much any item in the Dictionary. Dictionaries store elements in any order that is convenient for a lookup (so do sets).
This order is known for some implementations, but lists or arrays might fit better when the order of the elements is important. A Dictionary in .NET is an implementation of a hash table data structure (tree map is another map implementation).
try this :
foreach(var key in selectedDates.Keys)
{
var value = selectedDates[key];
}
Use this overload of Where:
var result = selectedDates.Where((d,i)=>i==0);
Try:
foreach (var date in selectedDates)
{
var item = date.Value;
}
Is that any Next function for a foreach in KeyValuePair ?
foreach (KeyValuePair<string, List<class>> KPV in dic )
{ }
or the only solution is using the traditional for loop with counter
Read MSDN Dictionary Class:
Represents a collection of keys and values.
While iterating through the dictionary, you work with KeyValuePair Structure, which represents a pair of key (here string) and value (here List<T>). So if the intention is to loop through List<T> in each pair, you need to access KeyValuePair.Value Property:
foreach (KeyValuePair<string, List<object>> KPV in dic)
{
foreach (object v in KPV.Value)
{
}
}
Also I replaced List<class> with List<object>, as definitely class is not a possible name for a type.
If each KeyValuePair.Key Property value is not important you may iterate through Dictionary.Values Property:
foreach (List<object> values in dic.Values)
{
foreach (object v in values)
{
}
}
KeyValuePair<TKey, TValue> objects can be enumerated if they are inside a Dictionary<TKey, TValue> object.
Inside a Dictionary you can use the Dictionary.Enumerator structure, which exposes the Dictionary.Enumerator.MoveNext() method, which may be the "Next" function you are looking for.
It would be nice if you can tell us what you intend to do inside that foreach code block.
So I have a concurrent dictionary defined as such
ConcurrentDictionary<string, ConcurrentDictionary<string, ConcurrentDictionary<string, SomeObject>>>();
I know that seems a little convoluted but the structure is valid...
Now my problem is that I have say x number of instances of these dictionaries for x different sources and for statistical purposes they need to be merged/amalgamated/aggregated into one single dictionary of the same structure...
Anyone any ideas on the best approach? I know I could create a new dictionary of the same structure; loop through each of the dictionaries to be amalgamated and at each level checking the new dictionary for those keys etc and adding or updating based on the result of that determination...
But that seems slightly unwieldy to me... any LINQ geniuses out there that could lend a hand?
[Note - I just made one important edit - the output dictionary is of the exact same structure as the input dictionaries]
LINQ doesn't help here, as you don't want to query a collection but manipulate one.
As said in the comments above, using a ConcurrentDictionary<Tuple<string, string, string>, SomeObject> would simplify things a bit. You could do the following then:
using MyDict = ConcurrentDictionary<Tuple<string, string, string>, SomeObject>;
MyDict Merge(IEnumerable<MyDict> dicts)
{
MyDict result = new MyDict();
foreach (var dict in dicts)
{
foreach (var kvp in dict)
{
result.AddOrUpdate(
kvp.Key, // If the key does not exist, add the value;
kvp.Value, // otherwise, combine the two values.
(key, value) => Combine(value, kvp.Value)
);
}
}
return result;
}
I have C# Dictionary.
Dictionary<string, string> map = new Dictionary<string, string>();
map["x"] = "1";
map["z"] = "2";
map["y"] = "0";
When I get the keys with foreach, I get the value of "x"-"z"-"y". And this is the sequence that I give input to the map.
foreach (var pair in map)
{
Console.WriteLine(pair.Key);
}
Is this guaranteed behavior? I mean, with Dictionary, do I always get the elements in FIFO way with foreach?
Nope, A dictionary is not guaranteed to order its contents in the way they were inserted.
To quote the blurb from MSDN:
'For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair(Of TKey, TValue) structure representing a value and its key. The order in which the items are returned is undefined.'
They are typically ordered by the key - x, y, z in your case.