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
}
}
}
}
}
Related
I am trying to get the list of items inside of a quickbooks database. I have the following snippet of code:
IItemServiceRet itemServiceRet = itemRet.ItemServiceRet;
TestItem item = new TestItem();
item.Name = itemServiceRet.Name.GetValue();
item.Desc = itemServiceRet.ORSalesPurchase.SalesOrPurchase.Desc.GetValue();
item.Rate = itemServiceRet.ORSalesPurchase.SalesOrPurchase.ORPrice.Price.GetValue().ToString();
item.ItemType = "Service";
item.QBID = itemServiceRet.ListID.GetValue();
item.EditSeq = itemServiceRet.EditSequence.GetValue();
The code fails on the line:
item.Desc = itemServiceRet.ORSalesPurchase.SalesOrPurchase.Desc.GetValue();
"Object reference not set to an instance of an object"
Because that particular service item in the QB database does not have a description. I was curious if there was a 'clean' way to check for null values without having to have each line include an if statement checking if GetValue() returns null?
Edit: After trying Andrew Cooper's solution of:
item.Desc = itemServiceRet.ORSalesPurchase.SalesOrPurchase.Desc == null ? null : itemServiceRet.ORSalesPurchase.SalesOrPurchase.Desc.GetValue();
It still throws the exception:
Object reference not set to an instance of an object
Its as if GetValue() returns nothing at all if there is no description, which wouldn't make much sense.
You could use the ternary operator like this:
item.Desc = itemServiceRet.ORSalesPurchase.SalesOrPurchase.Desc == null ? null : itemServiceRet.ORSalesPurchase.SalesOrPurchase.Desc.GetValue();
But that's pretty ugly.
Best bet is to create a helper method that takes whatever type Desc and wraps the above logic.
I don't think there's any better solution, as you can't access the functions of a null object. I typically create a constructor for my items that does the checking so I only have to do that once. So in your example:
TestItem item = new TestItem(itemRet.ItemServiceRet);
The constructor would look like this:
public TestItem(IItemServiceRet i)
{
if(i.Name != null) this.Name = i.Name.GetValue();
if(i.ORSalesPurchase != null)
if(i.ORSalesPurchase.SalesOrPurchase != null)
{
if(i.ORSalesPurchase.SalesOrPurchase.Desc != null) this.Desc = i.ORSalesPurchase.SalesOrPurchase.Desc.GetValue();
if(i.ORSalesPurchase.SalesOrPurchase.ORPrice != null)
if(i.ORSalesPurchase.SalesOrPurchase.ORPrice.Price != null) this.Price = i.ORSalesPurchase.SalesOrPurchase.ORPrice.Price.GetValue();
}
}Keep in mind that this does work well for strings, as an empty string is usually the same as a blank field, but for number fields in QuickBooks this may cause problems. For example, an Invoice line can have a blank quantity field (which is a double). A double will default to the value of 0.0, but a blank quantity field in QuickBooks is treated as a quantity of 1.0. This can also cause problems with dates, as QuickBooks can have null date fields.
Is it possible somethings like this:
var userAggregazione;
if (userAggregazione = YouTube.Actions.IsAccessTokenValid() != null)
{
}
IsAccessTokenValid() returns a userAggregazione instance or null. So, inside the if, I'd like to setup var userAggregazione, and check if it is null or not.
Is it possible?
not sure if I understand but let me attempt:
var userAggregazione = YouTube.Actions.IsAccessTokenValid();
if (userAggregazione == null)
{
// userAggregazione is null - do something
}
else
{
// it is not null - do something
}
It will work if there's an extra parentheses around the assignment, so that it will get evaluated before the != comparison.
MyClass userAggregazione;
if ((userAggregazione = YouTube.Actions.IsAccessTokenValid()) != null)
{}
edit2:
I assume the example is simplified, because normally you should do like this for clarity:
//my style preference is also to not use 'var' anyway
//when getting value from a function
//because it's not clear what the type is.
MyClass userAggregazione = YouTube.Actions.IsAccessTokenValid();
if (userAggregazione != null)
{}
Yes it is, you need to add some braces:
if ((userAggregazione = YouTube.Actions.IsAccessTokenValid()) != null)
Just ensure that IsAccessTokeValid does not throw any exceptions
what i am trying to do is check whether an item in a list box is selected.
The method is being run on a separate thread so i would need to use a method invoker i believe.
string list = "";
lbxList.Invoke(new MethodInvoker(delegate { list = lbxList.SelectedItem.ToString(); }));
if (list != null)
{
//do something
}
this code will blow up if the selected item is null because the string list wont hold it, so i would need a way to combine the top 2 lines into an if statement checking for null.
Thanks
This should do:
string list = "";
lbxList.Invoke(new MethodInvoker(delegate
{
if (lbxList.SelectedItem != null)
list = lbxList.SelectedItem.ToString();
}));
//do something
Just place the if-statement inside the anonymous method.
Note that .ToString is highly unlikely to ever return null for anything, the documentation of object.ToString states that overriding types should implement the method to return a meaningful value. Since we already know that .SelectedItem is not null, checking for null is not really necessary. You can leave it in if you really want, but if you're afraid that .ToString should return null, I would instead change the code to this:
string list = "";
lbxList.Invoke(new MethodInvoker(delegate
{
if (lbxList.SelectedItem != null)
list = lbxList.SelectedItem.ToString() ?? string.Empty;
}));
//do something
Does FirstOrDefault return a reference to the item in the collection or the value of the item?
var obj = myCollection.FirstOrDefault(x => x.Param == "match condition");
if (obj != null)
{
obj = newObjectOfCollectionType; //if found, replace with the changed record
}
Will this code replace the object reference in the myCollection with the new object, or will it do nothing to myCollection?
var obj = myCollection.FirstOrDefault(x => x.Param == "match condition");
if (obj != null)
{
obj = newObjectOfCollectionType; --> this will not reflect in the collection
}
var obj = myCollection.FirstOrDefault(x => x.Param == "match condition");
if (obj != null)
{
obj.Property = newValue; --> this will reflect in your object in the original collection
}
It does nothing to the collection. You can change the collection like this:
int index = myCollection.FindIndex(x => x.Param == "match condition");
if (index != -1)
{
myCollection[index] = newObjectOfCollectionType;
}
it will do nothing; obj is a reference to the object (if the collection is of a reference type), and not the object itself.
If the collection is of a primitive type, then obj will be a copy of the value in the collection, and, again- this means that the collection will not change.
Edit:
to replace the object, it depends what your collection's type is.
If it's IEnumerable<T>, then it's not mutable, and you won't be able to change it.
The best option you have is to create a new collection and modify that, like so-
T [] array = myCollection.ToArray();
array[index] = newObject;
It returns the value that's in the collection. But that value, in your case, is a reference.
It does not return the position. Your code will not change the collection.
If the sequence is a sequence of reference types, the reference is returned. Otherwise, the value is returned.
But, anyway, this line:
obj = newObjectOfCollectionType
does nothing with the sequence content, regardless of sequence's item type.
Inside the source code of Linq method is used foreach iterator which returns the element of IEnumerable collection.
foreach (TSource element in source) {
if (predicate(element)) return element;
}
The C# language specification states (8.8.4)
"The iteration variable corresponds to a read-only local variable with
a scope that extends over the embedded statement."
That is we get a readonly element. For ref types the modifier readonly allows change condition of an object but disallows changing the reference for an object.
I am using PetaPoco Micro-ORM with C# 4.0.
The code below retrieves a single row from the database:
var result = db.SingleOrDefault<TdUsers>(getUserQuery);
I would like to check whether or not the result contains any rows, and whether is null. What is the best way to do this?
if (result == null || result.Count() == 0) {
// Checks whether the entire result is null OR
// contains no resulting records.
}
I think the problem is not in your check for null, because linq is lazy loading. Your error is in using the expression db.SingleOrDefault<TdUsers>(getUserQuery);.
.Single<T>(expression) does not return null - it errors if the result returns no values.
.SingleOrDefault<T>(expression), however, returns a null value if the expression results in no values - and therefore is best combined with an if (result == null) type check, as you're using here.
var result = db.SingleOrDefault<TdUsers>(getUserQuery);
In above code SingleOrDefault will return null vale or the specified
generic type(it's known on runtime).
Inorder to check whether the returned values is null or not you can simply use
if(result!=null)
{
//do your code stuff
}
else
{
//stuff do be done in case where result==null
}
You could do:
result.ToList() // Convert result to a list
if (result.Any()) {
// result is not null
}
var v = result.ToList();
now check
if (v is not null)
{
}
else if (v.Count()>0)
{
}