0

I am having problem in performing OrderBy on a sub-property of an Object.

I have two separate Models as listed below:

PersonModel:

public class PersonModel 
{
   public string Name { get; set;}
   public DeptModel Dept { get; set; }
}

DeptModel

public class DeptModel 
{
   public int DeptId { get; set;}
   public string DeptName { get; set;}
}

I had used automapper to map the relation between those two class and I am able to retrieve data properly.

After the data had been retrieved, I am trying to implement order by using linq on the DeptName object. Then it is showing an error "Object reference not set to an instance of an object."

The result is retrieving data as IList < PersonModel >. If Debug over here it is showing the correct data at this point.

Then I am performing the OrderBy on the retrieved data and it is crashing over here.

var tmp = result.OrderBy(x => x.Dept.DeptName).ToList();

I am not sure why I getting this error. Any suggestions on resolving the issue is greatly appreciated.

Rocky
  • 119
  • 10
  • Most likely `x` or `Dept` is null. When you try to access it's properties, you get the exception. Put a breakpoint inside the lambda to see it's values at runtime. – gunr2171 Jun 16 '14 at 16:47
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – gunr2171 Jun 16 '14 at 16:48
  • Hey thanks.. There are some empty values and it is only causing the issue. Thanks a lot for your help – Rocky Jun 16 '14 at 17:38

1 Answers1

1

You need to make sure you are not using null in a default comparison. This is a simple example:

var tmp = result.OrderBy(x => ((x.Dept == null) || (x.Dept.Deptname == null)) ? "" : x.Dept.DeptName).ToList();

If you want a really nice solution though, you should implement your own Comparator See more here:

Use own IComparer<T> with Linq OrderBy

Community
  • 1
  • 1
Lajos Arpad
  • 45,912
  • 26
  • 82
  • 148
  • Thanks!! Your solution had fixed my issue. I will also try to implement my own Comparator and will see how that goes. Thanks – Rocky Jun 16 '14 at 17:35
  • 1
    You are welcome. The solution I gave is a quick solution. A much more elegant and beautiful solution is to have your own comparator, possibly applicable for more entity types and search types. It is longer to implement, but it will surely pay off on the long run. On the other hand, everyone needs the quick solution first to solve the urgent tasks. – Lajos Arpad Jun 16 '14 at 17:38