-1

The model Monsters contains a field of type JewelDrop which contains a field of type float with the name BlessDrop.

I am trying to sort a List of type Monster based on the value inside Monster.JewelDrop.BlessDrop but whenever I try doing it I get a NullReferenceException

 

This is what I have tried doing so far, which gives me this exception:

return monsters.OrderByDescending(x => x.JewelDrop.SoulDrop).FirstOrDefault();

There is no difference if I use First(); or FirstOrDefault();

namespace ConsoleApp1
{
    class Monster
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int MonsterLevel { get; set; }
        public int Hp { get; set; }
        public int MinDmg { get; set; }
        public int MaxDmg { get; set; }
        public int MinEleDmg { get; set; }
        public int MaxEleDmg { get; set; }
        public int Defense { get; set; }
        public int EleDefense { get; set; }

        public JewelDrop JewelDrop { get; set; }
    }
}
namespace ConsoleApp1
{
    class JewelDrop
    {

        public int MonsterLevel { get; set; }
        public float BlessDrop { get; set; }
        public float SoulDrop { get; set; }
        public float LifeDrop { get; set; }
        public float CreationDrop { get; set; }
        public float ChaosDrop { get; set; }
    }
}
dubplay
  • 85
  • 1
  • 8

1 Answers1

3

It looks like either one of your monsters is null, or more likely, has a null JewelDrop value.

try

return monsters.OrderByDescending(x => x?.JewelDrop?.SoulDrop).FirstOrDefault();

See https://csharp.today/tag/elvis-operator/

mcintyre321
  • 12,996
  • 8
  • 66
  • 103