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());
}
Related
I'm using mastercard API. Link https://developer.mastercard.com/documentation/mastercom/6#api_transactions_debit_master_card_and_europe_dual_acquirer
I Have to get the value of these keys. (These are key from Dictionary List)
transactionSummaryList[0].authTransactionId
transactionSummaryList[0].clearingTransactionId
transactionSummaryList[0].singleMessageSummaryDetails.authTransaction.acquirerReferenceNumber
transactionSummaryList[0].singleMessageSummaryDetails.authTransaction.adviceReasonCode
...
My code so far
try
{
TransactionsDebitMasterCardAndEuropeDualAcquirer response = TransactionsDebitMasterCardAndEuropeDualAcquirer.searchForDebitMCMessageTransaction(transactionsValues);
OutputTransaction outputTransaction = new OutputTransaction();
foreach (Dictionary<String, Object> item in (List<Dictionary<String, Object>>)response["transactionSummaryList"])
{
TransactionSummary transactionSummary = new TransactionSummary();
transactionSummary.authTransactionId = Out(item, "authTransactionId").ToString();
transactionSummary.clearingTransactionId = Out(item, "clearingTransactionId").ToString();
Object aux = Out(item, "singleMessageSummaryDetails");
outputTransaction.transactionSummaryLists.Add(transactionSummary);
}
outputTransactions.Add(outputTransaction);
}
public static Object Out(Dictionary<String, Object> response, String key)
{
return response[key];
}
I'm facing trouble when i try to get values from singleMessageSummaryDetails Key.
All values that I want is inside Object aux, but i can't "reach" them.
You have case aux as an Object, therefore it doesn't know about any specific properties. Object is the base class that all other .NET classes inherit from.
If you want to get to a specific property they you'll need to cast your object to a specific type.
If you know the class type, then you can cast it directly using either;
public static YourClass Out(Dictionary<String, YourClass > response, String key) or MyClass myClassInstance = (YourClass)myObject;
If you don't know the type then you can use reflection. Its a bit more complicated but will be something like;
Type myType = myObject.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());
foreach (PropertyInfo prop in props)
{
object propValue = prop.GetValue(myObject, null);
// Do something with propValue
}
I finally got it!
To make this work, first I turn the mastercard answer in a JSON.
Them I put it simple and easy in my object (DeserializeObject).
try
{
TransactionsDebitMasterCardAndEuropeDualAcquirer response = TransactionsDebitMasterCardAndEuropeDualAcquirer.searchForDebitMCMessageTransaction(transactionsValues);
OutputTransaction outputTransaction = new OutputTransaction();
var aux = JsonConvert.SerializeObject(response);
outputTransaction = JsonConvert.DeserializeObject<OutputTransaction>(aux);
outputTransactions.Add(outputTransaction);
}
Thanks so much for your answer #Mark Cooper, helps me a lot.
Sry for my bad english.
Thanks again.
I have a string variable which holds some value and I want to be able to check if that string exists in a dictionary as a key with its variable name.
For a clearer understanding as you can see in the following code;
string searchDuration = "200";
var response = new Dictionary<string, string>()
{
{"searchDuration","200"},
{"minRssi", "-70"},
{"optionalFilter","NO_FILTERS_ACTIVE_SCANNING"},
{"txPowerLevel","200"},
{"peripheralId","123wrong"}
};
I'm able to use ContainsKey method as following;
if (response.ContainsKey("searchDuration"))
if (searchDuration == pair.Value)
isEqual = true;
But I don't(actually can't) use it this way because;
I need to pass in every string variable dynamically, I can't write every variable name as a string to pass in to ConstainsKey method
It only check values and there might be multiple values with "200", this situation gives me false results.
I want to compare the value "200" only with related key which is "searchDuration", not with "txPowerLevel" which has the same value.
Is there a way to check whether a string variable exists as a key in a dictionary to compare it's value with dictionary members?
I'd suggest this approach:
string searchDuration = "200";
var response = new Dictionary<string, string>()
{
{"searchDuration","200"},
{"minRssi", "-70"},
{"optionalFilter","NO_FILTERS_ACTIVE_SCANNING"},
{"txPowerLevel","-16"},
{"peripheralId","123wrong"}
};
var wasItThere = response.TryGetValue(nameof(searchDuration), out var value);
Console.WriteLine(wasItThere && (value == searchDuration));
TryGetValue is better than ContainsKey since it gets the value at the same time as checking whether the key is there.
nameof is used to convert the variable name to its string representation.
I have explicitly not used pair.Value since that code in your original question strongly implies you are iterating through the Dictionary. This is not a good idea (performance wise).
If the variables you want to compare are all part of an object, then you can inspect that object with reflection and compare what is found inside the object with what is present in the Dictionary. Here is how:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var obj = new { searchDuration = "200", txPowerLevel = "100", other = "123"};
var stringProperties = obj
.GetType()
.GetProperties()
.Where(pi => pi.PropertyType == typeof(string) && pi.GetGetMethod() != null)
.Select(pi => new
{
Name = pi.Name,
Value = pi.GetGetMethod().Invoke(obj, null)}
)
.ToList();
var response = new Dictionary<string, string>()
{
{"searchDuration","200"},
{"minRssi", "-70"},
{"optionalFilter","NO_FILTERS_ACTIVE_SCANNING"},
{"txPowerLevel","200"},
{"peripheralId","123wrong"}
};
foreach (var item in stringProperties)
{
string v;
response.TryGetValue(item.Name, out v);
Console.WriteLine(item.Name + ": obj value=" + item.Value + ", response value=" + (v ?? "--N/A--"));
}
}
}
Working Fiddle: https://dotnetfiddle.net/gUNbRq
If the items are present as local variables then it can probably also be done (e.g. see here), but I would recommend putting it in object to keep the values you want to inspect separate from other variables that your method needs and uses.
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 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());
}
}
I am having the list X with some string and null value . I am iterating the foreach loop to bind the value to the textbox. If I get any null values in my list X the foreach loop get terminated and getting the null exception how to handle it.
I am checking the condition inside the foreach loop, but I think it's not correct logically.
SPList _listObj = web.Lists[new Guid(listID)];
SPListItem item = _listObj.GetItemById(Convert.ToInt32(itemID));
foreach (SPField field in _listObj.Fields)
{
if (field.Title != Null)
{ //do some code}}
Try below code:
foreach(var x in Lists.Where(x => x.fiels != null))
{
}
Why don't you use it like this with null-coalescing operator
foreach (var item in feeList ?? new List<FeeBusiness>())
{
// your code
}
The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.
That code looks pretty suspicious to me.
Firstly, do you really have a list of lists? If so, I'd imagine you have to iterate over each element in the inner list as well:
foreach(List list in Lists)
{
foreach (var x in list)
{
if (x.fields != null)
// blah
else
// blah
}
}
Secondly, are you sure that the Lists variable doesn't contain any nulls? Possibly it's actually x which is null, and that's the cause of your Null Reference Exception:
foreach(List x in Lists)
{
if (x != null && x.fields != null)
// blah
else
// blah
}
The code provided is not correct. I suppose you want to check X for Null in foreach loop. If this is logically correct or not, instead only you may know as logic goes beyond the code provided and depends on where you actually use it.
I personally don't find nothing bad to check for nulls in foreach loop.
You also, for example, can use Linq to query first for Null values and after Non Null values. The matter of design choice.
Regards.
List x in Lists? You probably mean to do:
foreach(string x in listvar){
if(x != null)
// do something
}
And are the strings actually null or just empty? That is a difference.
foreach(string x in listvar){
if(x != "")
// do something
}
I suspect that the problem is in your incorrect implementation of the foreach loop which causes to pop null errors as the objects inside the loop do not exist.
string delimitedvalues = null;//"11,22,33";
foreach(var str in (delimitedvalues?? string.Empty).split(','))
{
string testvalue = "Test Value" + str;
}
Hope the above construct is useful!
You have to make sure that your object you are getting doesn't come back as null (your list, _listObj) before you ever iterate its fields. Even if you are certain the GUID you are passing in matches the list you are trying to get, you should be checking that object for being null, and checking for the number of fields, and if you get an item for the ID you are passing in:
SPList _listObj = web.Lists[new Guid(listID)];
if (_listObj != null) // do we have a list object?
{
if (_listObj.Fields.Count > 0) // do we have list columns on the list?
{
SPListItem item = _listObj.GetItemById(Convert.ToInt32(itemID));
if (item != null) // did our item ID get a hit?
{
foreach (SPField field in _listObj.Fields)
{
if (field.Title != null) // need lower case null, here
{
//do some code
}
}
}
}
}