如何在C# Linq中对可空对象进行排序?

oxcyiej7  于 2022-12-06  发布在  C#
关注(0)|答案(1)|浏览(264)

I have a method, which has a parameter for a List of custom objects in which there are also nullable objects which I need to order, but when I try to order and save back to a list I get a "System.NullReferenceException".
Parameter:

List<GameSortModel> models

GameSortModel (I want to sort a value in GameResult, where GameResult can be null):

public class GameSortModel
{
    public int? Place { get; set; }
    public int? ExerciseId { get; set; }
    public ClassModel Class { get; set; }
    public ExerciseModel? Exercise { get; set; }
    public GameResultModel GameResult { get; set; }
}

GameResultModel:

public class GameResultModel
{
    [Key]
    public int Id { get; set; }

    [Required]
    public int ClassId { get; set; }

    [Required]
    public int ExerciseId { get; set; }

    [Required]
    public double Result { get; set; }
}

I want to sort my List by GameResult.Result value. I tried doing this:

models = models.OrderBy(x => x.GameResult.Result).ToList();

And I got the error written above.
My expected Output in GameResult.Result: e.g. 10, 15.3, 18, null, null, null
I also need to make a way to order by Descending, so: e.g. 18, 15.3, 10, null, null, null
After that I have written some code to add the Place value in each GameSortModel and check if there are same values and give them the same place, and then display the results on the website.

uajslkp6

uajslkp61#

You can substitute null into double.PositiveInfinity or double.NegativeInfinity :

models = models
  .OrderBy(x => x.GameResult?.Result ?? double.PositiveInfinity)
  .ToList();

in case of descending

models = models
  .OrderByDescending(x => x.GameResult?.Result ?? double.NegativeInfinity)
  .ToList();

Here we use null propagation: if GameResult is null then GameResult?.Result will be null which we turn into infinity with ?? .
Please, fiddle

相关问题