LinQ OrderBy 在与项目内的 属性 字段一起使用时返回 System.NullReferenceException

LinQ OrderBy returning System.NullReferenceException when used with field of a property inside the item

模型 Monsters 包含一个类型为 JewelDrop 的字段,该字段包含一个类型为 float 且名称为 BlessDrop 的字段。

我正在尝试根据 Monster.JewelDrop.BlessDrop 中的值对类型 Monster 的列表进行排序,但每当我尝试这样做时,我都会得到 NullReferenceException

这是我到目前为止尝试做的,这给了我这个例外:

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

如果我使用First();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; }
    }
}

看起来您的其中一个怪物是空的,或者更有可能是空的 JewelDrop 值。

尝试

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

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