I use a 3rd party library and am un able to get the object arrays' content
IDictionary dic=SomeFunc(); // this function returns an IDictionary
and I use DictionaryEntry to get its content
foreach(DictionaryEntry de in dic)
{
//each of de.Value is implemented as a KeyValuePair<object,object>
//I have not yet learned how to read each de.Value's key and value pair
}
Could you offer me a hint to get the strings inside de.Value which is a dictionary of object to object ?
EDIT
Each value of de.Values is a key value pair of type "object" to "object". It reports error when I cast it to string
foreach (DictionaryEntry de in dic)
{
foreach(KeyValuePair<string,string> k in (Dictionary<string,string>)de.Values)
{
//error: instance is null
}
}
make use of is keywork
if(de.value is typeof(Dictionary))
//than do code
not sure but this will work
To access only the values, have this:
foreach (object value in dic.Values)
{
MessageBox.Show(value.ToString());
}
If you mean each value is Dictionary by its own right then you can have nested loop:
foreach (object value in dic.Values)
{
Dictionary<object, object> nestedDic = (Dictionary<object, object>)value;
foreach (object nestedValue in nestedDic.Values)
{
MessageBox.Show(nestedValue.ToString());
}
}
Related
I have received data of type object {System.Collections.Generic.Dictionary<string, object>}. Parsing this is pretty straightforward:
Dictionary<string, object> parsedData = data as Dictionary<string, object>;
Now I am trying to access parsedData["stringArr"] of type object {object[]}. I got stuck when trying to convert this object {object[]} to string[].
I can't even iterate this:
foreach (object o in parsedData["stringArr"]){}
//returns Exception("...'object' does not contain a public instance definition for GetEnumerator")
One way you could get the object values as string[] is to use the as cast, just like you did with the original data:
object data = new Dictionary<string, object>
{
{"stringArr", new[] {"item1", "item2", "item3"}},
};
var parsedData = data as Dictionary<string, object>;
// cast the object values to string[]
foreach (var o in parsedData["stringArr"] as string[])
{
Console.WriteLine(o);
}
// Output:
// item1
// item2
// item3
That's because parsedData["stringArr"] is an object, not a object[].
I think you want to change the dictionary type parameters:
Dictionary<string, object[]> parsedData = data as Dictionary<string, object[]>;
If you have a Dictionary<string, object>, and you know a particular key's value has a more specific type, cast it as that type:
foreach (string s in (string[])parsedData["stringArr"])
You will of course receive exceptions if the value at that key is not of that type. A "safer" way of doing it would be to check first:
if (parsedData["stringArr"] as string[] data != null)
{
foreach (string s in data)
{
...
}
}
First of all, thank you all for your energy to help me to solve it. I would just bash my keyboard for a few more hours without you. I can't understand why extra conversion to object[] is required yet, but what works is:
Dictionary<string, object> parsedData = data as Dictionary<string, object>;
if (parsedData.ContainsKey("stringArr"))
{
foreach (object o in parsedData["stringArr"] as object[])
{
string myString = o.ToString();
}
}
I have the method
HandleNotification(string message, Dictionary<string, object> additionalData, bool isActive)
and I would take the from additionalData the value.
I have this additional data:
Extracoins:4
I don't understand how I can take the value 4 from additionalData for a specific key Extracoins.
You can get a value from a Dictionary like this if your only interested in accessing one specific key.
object value = null;
additionalData.TryGetValue("Extracoins", out value);
That way object will be the value in the Dictionary or it will remain null if the value is not found.
Or you can do:
if (additionalData.ContainsKey("Extracoins"))
{
object value = additionalData["Extracoins"];
}
Finally if you wanted to iterate over all the values in the Dictionary until you get the correct value you could do:
object value = null;
foreach (KeyValuePair<string, object> pair in additionalData)
{
if (pair.Key == "Extracoins")
{
value = pair.Value;
}
}
I have gone through some of the post regarding this but couldn't get the solution. How to handle the null value here in the following code?
foreach (KeyValuePair<string, object> obj in mainList[i])
{
PList[i].Add(obj.Value.ToString());
}
I am getting null value (null reference exception) while trying to get object value in the list. I have tried something like this,
foreach (KeyValuePair<string, object> obj in mainList[i])
{
try
{
var check = obj.Value.ToString();
PList[i].Add(check);
}
catch(NullReferenceException)
{
var check = "Null";
PList[i].Add(check);
}
}
I can achieve my target using the second snippet (using try catch blocks) but it seems to be very slow. It takes almost 30 seconds to process this for loop. So is there any other way on how to handle this null Json value?
mainList = List<Dictionary<String,String>>.
PList = List<String>.
You can check if value is null before add it to list.
foreach (KeyValuePair<string, object> obj in mainList[i])
{
PList[i].Add(obj.Value == null ? "Null" : obj.Value.ToString());
}
I have this
hashtable has a
key "ids" and its values are [1,2,3]
List<long> ids= (List<long>)hashtable["ids"];
an error occurs when trying to cast. It says
Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'System.Collections.Generic.List`1[System.Int64]'.
I've been stuck for hours, any suggestions?
It would be helpful if you wrote in your question what are the values you expect to get and the definition of your hashtable.
Assuming You are trying to get [1,2,3] and your 'Value' is an array of long, try:
List<long> ids= hashtable["ids"].ToList();
public static List<dynamic> ToDynamicList(this Hashtable ht)
{
var result = new List<dynamic>();
foreach (DictionaryEntry de in ht)
{
result.Add(new { key = de.Key, value = de.Value });
}
return result;
}
I'm currently trying to write a Dump() method from LinqPad equivalent iin C# for my own amusment. I'm moving from Java to C# and this is an exercise rather than a business requirement. I've got almost everything working except for Dumping a Dictionary.
The problem is that KeyValuePair is a Value type. For most other Value types I simply call the ToString method but this is insufficient as the KeyValuePair may contain Enumerables and other objects with undesirable ToString methods. So I need to work out if it's a KeyValuePair and then cast it. In Java I could use wildcard generics for this but I don't know the equivalent in C#.
Your quest, given an object o, determine if it's a KeyValuePair and call Print on its key and value.
Print(object o) {
...
}
Thanks!
If you don't know the types stored in the KeyValuePair you need to exercise a bit of reflection code.
Let's look at what is needed:
First, let's ensure the value isn't null:
if (value != null)
{
Then, let's ensure the value is generic:
Type valueType = value.GetType();
if (valueType.IsGenericType)
{
Then, extract the generic type definition, which is KeyValuePair<,>:
Type baseType = valueType.GetGenericTypeDefinition();
if (baseType == typeof(KeyValuePair<,>))
{
Then extract the types of the values in it:
Type[] argTypes = baseType.GetGenericArguments();
Final code:
if (value != null)
{
Type valueType = value.GetType();
if (valueType.IsGenericType)
{
Type baseType = valueType.GetGenericTypeDefinition();
if (baseType == typeof(KeyValuePair<,>))
{
Type[] argTypes = baseType.GetGenericArguments();
// now process the values
}
}
}
If you've discovered that the object does indeed contain a KeyValuePair<TKey,TValue> you can extract the actual key and value like this:
object kvpKey = valueType.GetProperty("Key").GetValue(value, null);
object kvpValue = valueType.GetProperty("Value").GetValue(value, null);
Presuming you are using the generic KeyValuePair then you need probably want to test for a particular instantiation, such as one created using a string for both key and value:
public void Print(object o)
{
if (o == null)
return;
if (o is KeyValuePair<string, string>)
{
KeyValuePair<string, string> pair = (KeyValuePair<string, string>)o;
Console.WriteLine("{0} = {1}", pair.Key, pair.Value);
}
}
If you want to test for any type of KeyValuePair then you'll need to use reflection. Do you?
you have the is keyword
http://msdn.microsoft.com/es-es/library/scekt9xw(VS.80).aspx