3

I have an ObservableCollection, which I even check first to make sure it has elements. And yet I still get a nullReferenceException (only sometimes, this has never had an issue with the winrt 8.1 version, I am changing it to UWP.) The code is below, and it gives me the error where a.Url is:

if (sTumblrblog_gv_list.Count != 0)
{
    if (tumblogconfig.ShowNSFWBlogs)
        sTumblrGridView.ItemsSource = sTumblrblog_gv_list.OrderBy(a => a.Url);
    else
        sTumblrGridView.ItemsSource = sTumblrblog_gv_list.OrderBy(a => a.Url).Where(a => a.IsNsfw == false);
}

System.NullReferenceException was unhandled by user code
  HResult=-2147467261
  Message=Object reference not set to an instance of an object.
  Source=Tumblr-FIA
  StackTrace:
       at tumblr_fia.MainPage.<>c.<updatestats>b__47_1(sTumblrblog_gv a)
       at System.Linq.EnumerableSorter`2.ComputeKeys(TElement[] elements, Int32 count)
       at System.Linq.EnumerableSorter`1.Sort(TElement[] elements, Int32 count)
       at System.Linq.OrderedEnumerable`1.<GetEnumerator>d__1.MoveNext()
       at System.Runtime.InteropServices.WindowsRuntime.EnumeratorToIteratorAdapter`1.MoveN

ext()
       at System.Runtime.InteropServices.WindowsRuntime.EnumeratorToIteratorAdapter`1.get_HasCurrent()
  InnerException: 

I understand this error I believe, but I am checking that sTumblrblog_gv_list is not a null value. And I now have it under a try & catch. And still sometimes I receive the error.

user3395025
  • 135
  • 2
  • 7

2 Answers2

10

You could try

.OrderBy(a => a != null ? a.Url : null)

On C# 6 you have the syntax

.OrderBy(a => a?.Url)
Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
3

It seems like you have null value inside sTumblrblog_gv_list.

OrderBy(a => a.Url).Where(a => a.IsNsfw == false) - It's a lazy evaluation.

Try to write evaluation:

sTumblrGridView.ItemsSource = sTumblrblog_gv_list.OrderBy(a => a.Url).ToArray();
yvesmancera
  • 2,915
  • 5
  • 24
  • 33
Andection
  • 351
  • 1
  • 2
  • 10
  • 1
    If one of the items in `sTumblrGridView` is `null` then `sTumblrblog_gv_list.OrderBy(a => a.Url)` will still throw an exception. Maybe a `.Where(a => a != null)` is needed. – juharr Sep 17 '15 at 18:04
  • I think so to. It should be placed before the sorting – Andection Sep 17 '15 at 18:10