I have this line:
myobject.Ada = result.FirstOrDefault(m => m.Name == "Ada No").Value;
Sometimes result doesn't have "Ada No" and I get
Object reference not set to an instance of an object.
I wrote an if statement to avoid null reference exception :
if(result.FirstOrDefault(m => m.Name == "Ada No").Value != null)
{
myobject.Ada = result.FirstOrDefault(m => m.Name == "Ada No").Value;
}
But it didn't work either. How can I avoid this exception in this piece of code? How can I write if Ada No exists, work, if not don't work? Thanks.
FirstOrDefault will return null if there is not any object which meets the condition. And the exception will be thrown when the code is trying to access a member of a reference type variable that is set to null. So, you must check if the object's value is null or not before accessing it.
You can use null-propagation operator if you are using C# 6.0:
myobject.Ada = result.FirstOrDefault(m => m.Name == "Ada No")?.Value;
Or if you are using lower versions:
var firstObj = result.FirstOrDefault(m => m.Name == "Ada No");
if(firstObj != null)
{
myobject.Ada = firstObj.Value;
}
The other solution would be to check with Any if any member is existing that consists of Name equal to "Ada No"
Be aware that result isn't null either!
But the null propagation way would be less to write, so it depends on you preference how you want to read your code and if it is some performance critical piece of code
if(result != null && result.Any(m => m.Name == "Ada No"))
{
myobject.Ada = result.FirstOrDefault(m => m.Name == "Ada No").Value;
}
Related
I am working on WPF application. In which I am trying to fetch records from list as per required condition. But when there is no any record found then it's giving me object reference not found error.
var recordList = _outputVariables.ToList().Where(X => X.symbolName == _symbolName).ToList();
if (recordList != null)
{
//more coding...
}
so as shown in code when _outputVariables have no any record match as per _symbolName then it's giving error of Object reference not set to an instance of an object.' and X was null.. So how can I handle this issue ? please help for it.
Use the null-conditional operator that was introduced in C#6 (and don't call ToList() more than once):
var recordList = _outputVariables?.Where(X => X?.symbolName == _symbolName).ToList();
if (recordList != null)
{
//more coding...
}
var recordList = _outputVariables.ToList().Where(X => X.symbolName == _symbolName).ToList();
You currently loop through _outputVariables, but if it's null this will give an error, because null does not have a .ToList(). So you should add a ? after your _outputVariables, so it will return null instead of an exception when it's null.
Same goes for X. If X is null and you try to get the property symbolName, you will get an error, because null doesn't have a property called symbolName. So you want to add a ? here too. So it will return null instead of an exception.
Leaving you with: var recordList = _outputVariables?.ToList().Where(X => X?.symbolName == _symbolName).ToList();
You can use like below as well
if (_outputVariables != null && _outputVariables.Count > 0)
{
var recordList = _outputVariables.Where(X => X != null && !string.IsNullOrEmpty(X.symbolName) && X.symbolName == _symbolName);
}
You can try this
if(_outputVariables!=null)
{
var recordList = _outputVariables.Where(X => X.symbolName ==_symbolName).ToList();
}
if (recordList != null)
{
//more coding...
}
I have a .Any() Linq Method:
db.MyTable.Any(x => x.Year == MyObj.Year && x.Quarter == MyObj.Quarter && x.Week == MyObj.Week)
That is returning the error:
System.InvalidOperationException occurred
HResult=0x80131509
Message=Sequence contains no matching element
Source=EntityFramework
However the MSDN documentation states that the .Any method returns "true if the source sequence contains any elements; otherwise, false."
Why is this method throwing the exception instead of returning False?
With this little code it is fairly difficult to see what the cause is. It certainly is not in this part of the code.
Try to do some debugging, use the debugger to check all values, or write some Debugging statements before you perform your function:
// Check myObj
MyObjectType myObj = ... // instead of var, so you are certain you have the right type
Debug.Assert(myObj != null);
// only if Year, Quarter, Week are classes:
Debug.Assert(myObj.Year != null);
Debug.Assert(myObj.Quarter != null);
Debug.Assert(myObj.Week != null);
// check your db:
Debug.Assert(db != null);
Debug.Assert(db.MyTable != null);
int count1 = db.MyTable.Count();
int count2 = db.MyTable
.Where(x => x.Year == MyObj.Year
&& x.Quarter == MyObj.Quarter
&& x.Week == MyObj.Week)
.Count();
bool hasAny = db.MyTable
.Where(x => x.Year == MyObj.Year
&& x.Quarter == MyObj.Quarter
&& x.Week == MyObj.Week)
.Any();
// if all this works, your statement should also work
hasAny = db.MyTable
.Any(x => x.Year == MyObj.Year
&& x.Quarter == MyObj.Quarter
&& x.Week == MyObj.Week);
Is hard to see, with your example but probably you must check if you have Null values in "MyTable" and the datatypes of MyTable.Year,MyTable.Quarter and MyTable.Week match with the sames in MyObj...
Ive been having some trouble trying to get this linq statement to work. I am setting up a search using linq queries. What i want to do is if a search is null or empty, have it ignore that part of the filtering. So what i have set up is many where clauses that short circuit the where clause like so:
tvContent.LoadContent(
Live.Ringtones
.Where(x => cbSeller.SelectedValue== null ||
x.Property.SellerID == (int)cbSeller.SelectedValue)
.Where(x => cbProperty.SelectedValue==null ||
x.PropertyID == (int)cbProperty.SelectedValue)
.Where(x => string.IsNullOrEmpty(tbContentID.Text) ||
x.RingtoneID == ContentID)
.Where(x => string.IsNullOrEmpty(tbContentName.Text) ||
x.RingtoneName == tbContentName.Text).ToList());
But when I do this I keep getting null reference issues.
cbProperty, is empty, and selectedValue does show up null when I debug, but it still says there's a null reference issue. What am I doing wrong?
Why are you putting an invariant into the where clauses?
var ringtones = Live.Ringtones;
if (cbSeller.SelectedValue!= null)
ringtones = ringtones.Where(x=> x.Property.SellerID
== (int)cbSeller.SelectedValue);
if (cbProperty.SelectedValue!= null)
ringtones = ringtones.Where(x=> x.PropertyID
== (int)cbProperty.SelectedValue);
if(!string.IsNullOrEmpty(tbContentID.Text))
ringtones.Where(x=> x.RingtoneID == ContentID)
if(!string.IsNullOrEmpty(tbContentName.Text) )
ringtones.Where(x => x.RingtoneName == tbContentName.Text)
tvContent.LoadContent(ringtones.ToList());
Here is my code:
string displayName = Dictionary.FirstOrDefault(x => x.Value.ID == long.Parse(options.ID)).Value.DisplayName;
The code works fine if x.Value.ID matches options.ID. However, I get a NullReferenceException if it doesn't.
FirstOrDefault returns the default value of a type if no item matches the predicate. For reference types that is null. Thats the reason for the exception.
So you just have to check for null first:
string displayName = null;
var keyValue = Dictionary
.FirstOrDefault(x => x.Value.ID == long.Parse(options.ID));
if(keyValue != null)
{
displayName = keyValue.Value.DisplayName;
}
But what is the key of the dictionary if you are searching in the values? A Dictionary<tKey,TValue> is used to find a value by the key. Maybe you should refactor it.
Another option is to provide a default value with DefaultIfEmpty:
string displayName = Dictionary
.Where(kv => kv.Value.ID == long.Parse(options.ID))
.Select(kv => kv.Value.DisplayName) // not a problem even if no item matches
.DefaultIfEmpty("--Option unknown--") // or no argument -> null
.First(); // cannot cause an exception
You can use a combination of other LINQ methods to handle not matching condition:
var res = dictionary.Where(x => x.Value.ID == someID)
.Select(x => x.Value.DisplayName)
.DefaultIfEmpty("Unknown")
.First();
Simply use the question mark trick for null checks:
string displayName = Dictionary.FirstOrDefault(x => x.Value.ID == long.Parse(options.ID))?.Value.DisplayName ?? "DEFINE A DEFAULT DISPLAY NAME HERE";
That is because FirstOrDefaultcan return null causing your following .Value to cause the exception. You need to change it to something like:
var myThing = things.FirstOrDefault(t => t.Id == idToFind);
if(myThing == null)
return; // we failed to find what we wanted
var displayName = myThing.DisplayName;
To add to the solutions, here is a LINQ statement that might help
Utilities.DIMENSION_MemTbl.Where(a => a.DIMENSION_ID == format.ContentBrief.DimensionID).Select(a=>a.DIMENSION1).DefaultIfEmpty("").FirstOrDefault();
The result will be an empty string if the result of the query is a null..
This answer is for those of us who need a visual write up (like me :)
In the code screenshot below, a NullReferenceException will be thrown, the root cause is the ReferenceIdentification_02 property.
When debugging, we see that the orderLine.REF array, I am querying does not include a matching object whose ReferenceIdentificationQualifier_01 value == "RU", so at that point FirstOrDefault() return value is NULL
to prevent the NullReferenceException, I do a FirstOrDefault() on the orderLine.REF array first. If the returned value is not null then I retrieve the value.
i assume you are working with nullable datatypes, you can do something like this:
var t = things.Where(x => x!=null && x.Value.ID == long.Parse(options.ID)).FirstOrDefault();
var res = t == null ? "" : t.Value;
you can use with 'Where' statement with FirstOrDefault().
like this.
var modelItem = _dbcontext.ModelName.Where(n => n.NewsTagId == newsTag.Id).FirstOrDefault();
It returns first item if does not match query.
It is better practice to check the NULL after query.
if(modelItem == null)
{
return "Not Found."
}
else
{
// continue process
}
I have an list of objects that contains another object in it.
List<MyClass> myClass = new List<MyClass>();
I want to do some linq like this
myClass.Where(x => x.MyOtherObject.Name = "Name").ToList();
Thing is sometimes "MyOtherObject" is null. How do I check for this?
Simple, just add an AND clause to check if it's not null:
myClass.Where(x => x.MyOtherObject != null && x.MyOtherObject.Name = "Name").ToList();
As of C# 6, you can also use a null conditional operator ?.:
myClass.Where(x => x.MyOtherObject?.Name == "Name").ToList();
This will essentially resolve the Name property to null if MyOtherObject is null, which will fail the comparison with "Name".
Try it online
You can just make your predicate check for null...
myClass.Where(x => (x.MyOtherObject == null) ? false : x.MyOtherObject.Name == "Name").ToList();
I would do something like this:
myClass.Where(x => x.MyOtherObject != null)
.Where(y => y.MyOtherObject.Name = "Name")
.ToList();