How to put in a DT some elements from a Dictionary

Hi guys,

I have an array of a Dictionary (String,Object), this dictionary has too many information so as I need just some data to work with I thought that will be better to work with a DT

So I created a DT, and when I start to populate the DT I am getting an error, I guess because some of the values are null but I dont know how to fix that error.

Any idea?

You can use an in-line if statement to check if it is null before attempting to use the object.

If(String.IsNullOrEmpty(YourDictionary("YourKey").ToString),String.Empty,YourDictionary("YourKey")

This will change any null/missing dictionary values to be an empty string wherever you’re putting it. Note that it doesn’t actually change the dictionary, it just changes the value when using it in the one in-line statement.

Another note is that if the key is missing (e.g. “YourKey” doesn’t exist in the dictionary) then you will get a different error. In that case, you need to search if KeyExists before referencing the key

A dictionary is a much better data type to use though. It is much quicker & less resource intensive if you are planning on using a “lookup table” instead.

Thanks Dave, I tried that but is not working … I just figure out that doing an object that is null to String is the problem. I tried dic(“key”).tostring and that doesnt work … but now I tried … Convert.ToString(dic(“key”)) and that is working fine … Dont know what is the difference between Obj.ToString and Convert.ToString(Obj) Do you know?.. but the second one is working

this would give an exception if it was null cause of your ToString…
If(String.IsNullOrEmpty(YourDictionary(“YourKey”).ToString)

@bcorrea and @carmen oops, you are right, if the object you are referencing in the dictionary value is null, then it couldn’t convert to string.

You would have to just check if it is nothing. Change it so the condition is: IsNothing(YourDictionary("YourKey")) This looks up the key in the dictionary, and if it returns a null value, then the condition will be True. Keep in mind that if the key does not exist that you will still get an error

2 Likes

Those are actually very different things:
Obj.ToString will give an error if Obj is null as you tried to use something that “dont exist yet”
Convert.ToString(Obj) will never give an error because anything can be converted to string, even a null value is ok for a string type.

ok thanks for the aclaration.

1 Like