Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.NullReferenceException in a linq sort OrderBy(a => a.Url), UWP [duplicate]

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.

like image 778
user3395025 Avatar asked Jun 01 '26 13:06

user3395025


2 Answers

You could try

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

On C# 6 you have the syntax

.OrderBy(a => a?.Url)
like image 179
Jeppe Stig Nielsen Avatar answered Jun 04 '26 01:06

Jeppe Stig Nielsen


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();
like image 32
Andection Avatar answered Jun 04 '26 02:06

Andection