var nextItem = ql.Fragments.Where(x => x.AddedToFinal.Equals(false));
x.AddedToFinal is bool and ql.Fragments is not null
this linq statement sporadically get this exception:
System.NullReferenceException: Object reference not set to an instance
of an object.
at System.Linq.Enumerable.WhereListIterator1.MoveNext() at
System.Linq.Enumerable.Count[TSource](IEnumerable1 source)
There is a question already that should have answered this( linq where clause and count result in null exception) but this is impossible since the field is a not null Boolean, and this isn't a database object it is a list
Just added:
The code where I populate the list is multi-threaded. different fragments add items to the list after they have retrieved the items from the db:
.....
xe = XElement.Parse(result);
XmlFragment xf = new XmlFragment();
xf.Fragment = xe;
xf.LetterQueueOID = lq.LetterQueueOID;
xf.ParentGroupNodeName = ParentGroupNodeName;
xf.LinkingField = GroupNode.LinkingField;
xf.GroupNodeName = GroupNode.GroupNodeName;
lock (queuedLetters[lqOID])
{
if (lq.Fragments == null)
lq.Fragments = new List<XmlFragment>();
lq.Fragments.Add(xf);
}
ql.Fragments itself isn't null, but one of the elements in the enumeration is null. I'm guessing that is a problem in and of itself, but you could modify the statement to be:
var nextItem = ql.Fragments.Where(x => x != null &&
x.AddedToFinal.Equals(false));
Although that doesn't solve the problem of why one of the elements in the collection was null to begin with.
x.AddedToFinal is bool and ql.Fragments is not null this linq statement sporadically get this exception:
Then one of the elements of ql.Fragments is null so that
x.AddedToFinal
is throwing a NullReferenceException for some value of x in ql.Fragments. You could say
var nextItem = ql.Fragments
.Where(x => x != null)
.Where(x => !x.AddedToFinal);
but you should probably find out why there are null elements in your collection.
I would check if x is null
var nextItem = ql.Fragments.Where(x => x != null && x.AddedToFinal.Equals(false));
Are you sure all rows have a value for AddedToFinal ?!!
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Linq.Enumerable.WhereListIterator1.MoveNext() at System.Linq.Enumerable.Count[TSource](IEnumerable1 source)
As you can see in exception Iterator can't move or read next row.
Be sure all rows have a value for this field.
Related
I have a list of a class object, I need to filter that list with element which starts with these letters "GHB" and then set a listview control dataconext to it to display the elements
if(myList.ToList().FindIndex(x=> x.Name !=null)!=-1 )
{
listview1.DataContext = myList.ToList().where(x=> x.Name.StarstWith("GHB"))
}
But it gives me an error when an element is null
It gives you the error because your if condition is actually useless. You check whether Name in at least one element is not null, if so you try to access the variable. This of course will fail, because you need only 1 element with a valid name and the rest still can have null values which will lead to the NullReferenceException
What you can do is: check in the where clause additionaly whether Name is not null and if so only then check whether it StartsWith("GHB"):
listview1.DataContext = myList.Where(x => x?.Name != null && x.Name.StartsWith("GHB")).ToList();
this way you can save yourself the if condition.
I guess what you where trying to check is if Name in all elements is not null. In this case you can use the All method:
if (myList.All(x=>x.Name != null)
EDIT: using the ? will avoid that Name is checked if an element in the List is entirely null:
myList.Where(x => x?.Name != null && x.Name.StartsWith("GHB")).ToList();
Try this:
listview1.DataContext = myList
.Where(x => x != null
&& !string.IsNullOrEmpty(x.Name)
&& x.Name.StarstWith("GHB"))
.ToList();
...and remove the if statement.
I have a List which holds > 10.000 items. I am doing a LINQ query on this
IEnumerable<Term> terms = from t in regionCollection
where t.Name == strRegion
select t;
if (terms != null)
{
m.RegId = Convert.ToInt32(terms.FirstOrDefault().CustomProperties["dbId"]);
}
If (terms !=null) is always not null! I have a feeling that the query is executed only if i try to access the single object inside the IEnumarable. Is this correct and if yes how can i check if my IEnumarable is not null?
Variable term will always have a value, it will never be null, because if query returns no results then terms will be empty enumerable. In your case you can update the code like this:
// Get first item of query or default value
var firstTerm = terms.FirstOrDefault();
// If there were no items, then firstTerm is null
if (firstTerm != null)
{
// This code block is only executed if the query had at least 1 item in results
m.RegId = Convert.ToInt32(firstTerm.CustomProperties["dbId"]);
}
I'm getting some unexpected behavior in my process. I'm doing the following.
IEnumerable<Thing> things = ...;
IEnumerable<Thing> subset = things.Where(a => a.SomeFlag);
String info = "null: " + (subset == null);
The above works and info tells me that the object isn't null. So I wish to check the number of the elements in subset by this.
IEnumerable<Thing> things = ...;
IEnumerable<Thing> subset = things.Where(a => a.SomeFlag);
String info = "null: " + (subset == null);
String count = subset.Count();
Now I get an exception giving me the error message:
Object reference not set to an instance of an object.
What do I miss?!
It's possible that one of the Thing's in subset is null. You can try this:
IEnumerable<Thing> subset = things.Where(a => a != null && a.SomeFlag);
Note that due to the way Linq's lazy evaluation, you won't get any exception you call .Where because all it's doing at that point is setting up a condition for filtering the elements of things. Only later when you call .Count is it actually evaluating the results.
Update: With the new null-condition operator in C# 6 (also called the safe navigation or 'Elvis' operator), we can do the same thing a bit more succinctly:
IEnumerable<Thing> subset = things.Where(a => a?.SomeFlag);
An IEnumerable<Thing> implies deferred execution.
In your first fragment subset and things are never enumerated.
In the second fragment, it is the call to Count() that enumerates the lists and only then it comes to light that one of the a is null in a => a.SomeFlag.
You can see what really happens here with a bit simplified example.
Test class:
public class Test
{
public int Value { get; set; }
}
And LINQ query on IEnumerable<Test>:
IEnumerable<Test> source = new List<Test>() {
new Test { Value = 10 },
null,
new Test { Value = 20 }
};
IEnumerable<Test> filteredSource = source.Where(x => x.Value > 10);
// return false
Console.WriteLine(filteredSource == null);
// throws NullReferenceException
Console.WriteLine(filteredSource.Count());
Why does it happens? Because filteredSource == null does not cause collection enumeration, so Where predicate is not being fired on any source collection element.
However, when you call Count() on filteredSource the predicate is being called on every item from source collection, and when it comes to an item which is null: null.Value > 10 throws the exception.
How to make it work? Extend the predicate with x != null check:
IEnumerable<Test> filteredSource = source.Where(x => x != null && x.Value > 10);
Ok, so suppose you had the following items in things:
Thing A SomeFlag = true
Thing B SomeFlag = false
null
Thing C SomeFlag = true
First you count all the items in things. So you iterate over 4 objects, find 4 objects, and know that the result is 4. Easy.
Now you want to count all of the items in subset which means you need to figure out which items are in subset in the first place. So you go about counting them:
Thing A .... A.SomeFlag is true, so count it
Thing B .... B.SomeFlag is not true, so don't count it
null .... null.SomeFlag NULLREFERENCEEXCEPTION
And that's where your error comes from.
Note that even if all of the elements in things are not null, you can still get a NullReferenceException if the .SomeFlag get accessor has a side effect that could cause a NullReferenceException.
Considering the following code
IEnumerable<String> query = null;
query = from x in xml.Descendants(xmlMasterContainerName).Descendants(xmlElementName)
let guid = x.Attribute("guid") ?? new XAttribute("guid", "-1")
where x.Attribute(xmlAttributeIdName).Value == xmlAttributeIdValue
select guid.Value;
I get the 'object reference not set' when trying query.ToList()
This is very probably caused by 'select guid.Value' when 'x.Attribute(xmlAttributeIdName).Value == xmlAttributeIdValue' does not exist.
How can I check the where statement for existing value before selecting?
Thanks
In XLinq, you usually don't use Attribute().Value directly, because of the exact error you are getting. Instead, you cast it. The cast will result in null if Attribute() returned null, so there will be no exception.
So, you would change your where clause to this:
where ((string)x.Attribute(xmlAttributeIdName)) == xmlAttributeIdValue
and your select to this:
select (string)guid
BTW: I would write that code like this:
var query = xml.Descendants(xmlMasterContainerName)
.Descendants(xmlElementName)
.Where(x => ((string)x.Attribute(xmlAttributeIdName)) ==
xmlAttributeIdValue)
.Select(x => (string)x.Attribute("guid") ?? "-1");
If there is no attribute xmlAttributeIdName you will get an exception accessing Value property. Use casting instead (it will return default value). Also you don't need to create attribute - you can simply return value:
IEnumerable<String> query = null;
query = from x in xml.Descendants(xmlMasterContainerName)
.Descendants(xmlElementName)
where (string)x.Attribute(xmlAttributeIdName) == xmlAttributeIdValue
select (string)x.Attribute("guid") ?? "-1";
I am getting this error when I try to retrieve some data. Here is how I am querying
using (_realtyContext = new realtydbEntities())
{
foreach (int yr in years)
{
var standard = (from feest in _realtyContext.FeeStandards
where feest.Year == yr && feest.FeeCategory.CategoryName == "PropertyFee"
select feest).SingleOrDefault();
var chargeItem = (from chrgItem in _realtyContext.PropertyFees
where chrgItem.FeeStandardID == standard.FeeStandardID
&& chrgItem.HousholdId == Householder.HouseholdID
select chrgItem).SingleOrDefault();
this._propertyFees.Add(chargeItem);
this._standards.Add(standard);
}
}
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
the error is on the 2nd query.(var chargeItem)
this query throw an error: var chargeItem =...
.SingleOrDefault() returns null when no records are found, and in the next statement you're using "standard" as if it is never null.
But that's just one of the many possible causes...
you have to check if standard is null. SingleOrDefault() will return null if there are no results