manni
manni

Reputation: 717

.net System.Collections.Generic.List<T>.sort nullable int

How do I sort a list on a nullable int property using System.Collections.Generic.List<T>.Sort?

Or do I have to do a manual sort because that's not possible?

Upvotes: 0

Views: 3712

Answers (2)

Chris Sinclair
Chris Sinclair

Reputation: 23208

Since they want null firsts, they can use the default sorting implementation:

List<int?> myList = new List<int?>() { 2, -3, null, 9 };

myList.Sort();

for (int i = 0; i < myList.Count; i++)
    Console.WriteLine(myList[i]);  //null, -3, 2, 9

If you do need a different order, use Peter Ritchie's solution.

EDIT: Just realized, this is probably for a nullable property of a class in the list, in which case use LINQ's default OrderBy implementation:

public class MyClass
{
    public int? Value;
}

List<MyClass> myList = new List<MyClass>()
{
    new MyClass() { Value = 2},
    new MyClass() { Value = -3},
    new MyClass() { Value = null},
    new MyClass() { Value = 9},
};

var sorted = myList.OrderBy(entry => entry.Value).ToList();

for (int i = 0; i < sorted.Count; i++)
    Console.WriteLine(sorted[i].Value); //null, -3, 2, 9

Another case, if you don't want to use LINQ, is to use the default comparer with the List.Sort method:

myList.Sort((x, y) =>
    {
        return System.Collections.Generic.Comparer<int?>.Default.Compare(x.Value, y.Value);
    });

Upvotes: 1

Peter Ritchie
Peter Ritchie

Reputation: 35870

First you need to decide how a null value compares with items with a value. Then you can perform the comparison. For example if you decide that null is always "less than" a non-null:

list.Sort((x,y) => {
  if(!x.Nullable.HasValue) {
     if(!y.Nullable.HasValue) return 0; // equal
     else return -1; // y is greater
  }
  else
  {
    if(!y.Nullable.HasValue) return 1; // x is greater
    if(x == y) return 0; // equal
    if(x < y) return -1; // y is greater
    else return 1;
  }
}

Upvotes: 7

Related Questions