Check system.nullreferenceexception - c#

My code as follows:
#{var UName = ((IEnumerable<Pollidut.ViewModels.ComboItem>)ViewBag.UnionList).FirstOrDefault(x => x.ID == item.UNION_NAME_ID).Name;<text>#UName</text>
if ViewBag.UnionList is empty then it troughs system.nullreferenceexception.How to check and validate this?

Well, you're calling FirstOrDefault - that returns null (or rather, the default value for the element type) if the sequence is empty. So you can detect that with a separate statement:
#{var sequence = (IEnumerable<Pollidut.ViewModels.ComboItem>)ViewBag.UnionList;
var first = sequence.FirstOrDefault(x => x.ID == item.UNION_NAME_ID);
var name = first == null ? "Some default name" : first.Name; }
<text>#UName</text>
In C# 6 it's easier using the null conditional operator, e.g.
var name = first?.Name ?? "Some default name";
(There's a slight difference here - if Name returns null, in the latter code you'd end up with the default name; in the former code you wouldn't.)

First of all, you should not be doing this kind of work in the View. It belongs in the Controller. So the cshtml should simply be:
<text>#ViewBag.UName</text>
And in the controller, use something like:
var tempUnion = UnionList.FirstOrDefault(x => x.ID == item.UNION_NAME_ID);
ViewBag.UName = tempUnion == null ? "" : tempUnion.Name;

Related

Filter a list of class with element which starts with specific letters

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.

Avoid NullReferenceException in LINQ Expression on Datatable column

I am stuck with null values in my Datatable "articles". Using LINQ to get a list of articles works for column ArticleId but with column "ArticleVariations" the null values are killing me.
var result = this.articles.AsEnumerable().Where(r =>r.Field<String>("ArticleId").Equals(artNo)); // works. no nulls there ;)
var result = this.articles.AsEnumerable().Where(r =>r.Field<String>("ArticleVariations").Equals(artNo)); // stuck with nulls here
If the column contains nulls, I get an NullReferenceException, Can I avoid this somehow and is it possible to merge both expressions?
You can use null-conditional and null-coalescing operators:
var result = this.articles.AsEnumerable()
.Where(r =>r.Field<String>("ArticleVariations")?.Equals(artNo) ?? false);
The problem obviously occurs because r.Field<String>("ArticleVariations") retuns null. Thus you have to check for null before calling Equals on it.
For that you can call multiple statements within a LINQ-expression:
var result = this.articles.AsEnumerable().Where(r => {
var res = r.Field<String>("ArticleVariations");
if (res != null) return res.Equals(artNo);
else return false;
});
If the field can be null then just reverse your test:
var result = this.articles.AsEnumerable().Where(r => artNo.Equals(r.Field<String>("ArticleVariations")));
Then all you need to do is check that artNo is not null before making the call:
List<Type> result;
if (string.IsNullOrWhiteSpace(artNo))
{
result = new List<Type>();
}
else
{
result = this.articles.... as before
}
Where just takes a function which returns a bool to determine if it should filter an item out of a collection. You can write it with a multi-statement body just like any other function to make nulls easier to deal with. Something like this should be a good starting point:
.Where(r => {
string articleVariations = r.Field<string>("ArticleVariations");
return articleVariations != null && articleVariations.Equals(artNo);
});
IF you want to combine those checks somehow to build a list where one or the other of the given fields matches your artNo, you can just add it to the function body.
If the column contains nulls, I get an NullReferenceException, Can I avoid this somehow
Avoid using instance Equals methods where possible. Use the respective operators or static Equals methods because they handle correctly nulls for you.
In your concrete case, the easiest way is to replace Equals with ==:
var result = this.articles.AsEnumerable()
.Where(r => r.Field<string>("ArticleId") == artNo);
var result = this.articles.AsEnumerable()
.Where(r => r.Field<string>("ArticleVariations") == artNo);
and is it possible to merge both expressions?
It depends on what do you mean by "merging" them. If you mean matching article or variation by the passed artNo, then you can use something like this
var result = this.articles.AsEnumerable()
.Where(r => r.Field<string>("ArticleId") == artNo
|| r => r.Field<string>("ArticleVariations") == artNo);

Better Way to Check for Null Value in Linq Path

Here is an example of an assignment to a linq path pulled from code first...
applicants = appRegistrations
.ToList()
.Select(c => new ApplicantList() {
PartnerType = c.Participant != null ? c.Participant.PartnerType != null ? c.Participant.PartnerType.PartnerTypeName : "" : ""
});
Notice the null checks - is there a more elegant way I can write this code considering Participant AND PartnerType could be null?
I just hate checking for nulls on each property.
You could check if one of both are null:
List<ApplicantList> applicants = appRegistrations
.Select(ar => c.Participant == null || c.Participant.PartnerType == null
? "" : c.Participant.PartnerType.PartnerTypeName)
.Select(str => new ApplicantList { PartnerType = str })
.ToList();
You can shorten it a little bit:
PartnerType = c.Participant != null && c.Participant.PartnerType != null
? c.Participant.PartnerType.PartnerTypeName
: ""
When you construct the objects such as Participant, make sure that the properties are never null. Think if null is a valid value for a Participant? If not then you should never allow it to be null. Take a constructor parameter and add a guard clause to check for nulls. Otherwise initialize them to a default value.
Also, see NULL Reference Pattern.

Check LINQ return is null for observable collection List

Data1 = new ObservableCollection<dsData1>(from itmGetAllData2 in GetAllData2
where itmGetAllData2.Name == strName
select itmGetAllData2)[0];
Above LINQ is working fine if there is a match between itmGetAllData2.Name == strName but if there is no record matching strName it is throwing an error.
Can anyone suggest how to handle this? I tried doing
.DefaultIfEmpty().Max(itmGetAllData2 => itmGetAllData2 == null ? "" : itmGetAllData2);
but it's giving casting error.
Your code could be simplified to:
Data1 = GetAllData2.FirstOrDefault(x => x.Name == strName);
If no matches are found, Data1 will be null. (that's what the OrDefault part adds) If you want to substitute a different value for null, you can do, e.g.
Data1 = GetAllData2.FirstOrDefault(x => x.Name == strName) ?? new dsData1();
The reason you are getting this error is because you are trying to access the first element of an empty query.
Use FirstOrDefault
var result = GetAllData2.FirstOrDefault(ad => ad.Name = strName);
if (result != null)
{
// Initalize your ObservableCollection here
}
You get this error when there is no match because [0] is trying to access the first object of a list that doesn't have any objects. Do this instead:
Data1 = GetAllData2.FirstOrDefault(d => d.Name == strName);
This will be the first item like you want, or null if none were found.

Lambda expression like Sql where value or null

I'm coding a search for an MVC app we're building, the thing is I would like to search by various properties of an object. In this particular case this is my expected behavior:
If both parameters are null or empty, return all.
If any parameter has a value, select all filtered by that parameter using Contains.
This is what I'm doing:
var model = _svc.GetList(q => q.Name == (string.IsNullOrEmpty(entity.Name) ? q.Name : entity.Name) &&
q.Description == (string.IsNullOrEmpty(entity.Description) ? q.Description : entity.Description));
This returns either all elements if both fields are null or empty, or any element that matches exactly the Name AND/OR Description.
The thing here is I would like this to behave as a Contains.
I've managed to get this working with one field:
var model = _svc.GetList(q => (string.IsNullOrEmpty(entity.Name) ||
q.Name.ToLower().Contains(entity.Name.ToLower()))).ToList();
But when I add the Description field, it throws a NullReferenceException: Object reference not set to an instance of an object.
Just to check I've tried this and it didn't work either:
var model = (from q in _svc.GetList()
where (string.IsNullOrEmpty(module.Name) ||
q.Name.ToLower().Contains(module.Name.ToLower()))
select q).ToList();
model = (from q in model
where (string.IsNullOrEmpty(module.Description) ||
q.Description.ToLower().Contains(module.Description.ToLower()))
select q).ToList();
Well, for a multi-optional-criteria search, you can do (asserting "module" is your "search class").
Simple, and (I think) more readable. Add a null check for the description and entity property of your model.
//take all elements
var model = _svc.GetList();
if (!string.IsNullOrEmpty(module.Description))
model = model.Where(m =>
m.Description != null &&
m.Description.ToLower().Contains(module.Description.ToLower());
if (!string.IsNullOrEmpty(module.Name))
model = model.Where(m =>
m.Name != null &&
m.Name.ToLower().Contains(module.Name.ToLower());
return module.ToList();
Null check, because a ToLower() on a null will raise a NRE !
This is a little ugly but should do the trick, you are getting the null reference because of entries with empty Description. If what you are doing with the Name is any clue, you are probably doing something like this q.Description.ToLower().Contains(..) without checking that q.Description is not null
var model = _svc.GetList(q =>
(string.IsNullOrEmpty(entity.Name) || string.IsNullOrEmpty(q.Name)
|| q.Name.ToLower().Contains(entity.Name.ToLower()))
&& (string.IsNullOrEmpty(entity. Description) || string.IsNullOrEmpty(q. Description)
|| q.Description.ToLower().Contains(entity. Description.ToLower())))

Categories

Resources