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.
1条答案
按热度按时间uajslkp61#
You can substitute
null
intodouble.PositiveInfinity
ordouble.NegativeInfinity
:in case of descending
Here we use null propagation: if
GameResult
isnull
thenGameResult?.Result
will benull
which we turn into infinity with??
.Please, fiddle