【问题标题】:Getting exception in order by in C# Linq在 C# Linq 中按顺序获取异常
【发布时间】:2014-10-02 00:19:23
【问题描述】:

有一个名为 ProccesXmlResponse 的方法,下面写了一行。

var myMessages = messages.OrderByDescending(x => x.MessageSentDate).ToList();

MessageSentDate 是 DateTime 的类型。我正在初始化消息对象。虽然我得到了以下异常。请帮助

Type : System.NullReferenceException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Message : Object reference not set to an instance of an object.
Source : PHOnline.Application.Service
Help link : 
Data : System.Collections.ListDictionaryInternal
TargetSite : System.DateTime <ProccesXmlResponse>b__6(PHOnline.Application.Model.DTO.Vitality.MyMessage)
HResult : -2147467261
Stack Trace :    at PHOnline.Application.Service.Implementations.Vitality.MyMessagesResponseMapper.<ProccesXmlResponse>b__6(MyMessage x)
   at System.Linq.EnumerableSorter`2.ComputeKeys(TElement[] elements, Int32 count)
   at System.Linq.EnumerableSorter`1.Sort(TElement[] elements, Int32 count)
   at System.Linq.OrderedEnumerable`1.<GetEnumerator>d__0.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at PHOnline.Application.Service.Implementations.Vitality.MyMessagesResponseMapper.ProccesXmlResponse(String response)

模型类: 公共类 MyMessage { /// /// 获取或设置EntityNumber。 /// 公共字符串 MessageID { 获取;放; }

    /// <summary>
    ///     Gets or sets EntityNumber.
    /// </summary>
    public string MessageSubject { get; set; }

    /// <summary>
    ///     Gets or sets EntityNumber.
    /// </summary>
    public DateTime MessageSentDate { get; set; }

    /// <summary>
    ///     Gets or sets EntityNumber.
    /// </summary>
    public string Read { get; set; }

    /// <summary>
    ///     Gets or sets EntityNumber.
    /// </summary>
    public string FileName { get; set; }

    /// <summary>
    ///     Gets or sets EntityNumber.
    /// </summary>
    public string MIMEType { get; set; }

    /// <summary>
    ///     Gets or sets EntityNumber.
    /// </summary>
    public string AttachmentContent { get; set; }
}

【问题讨论】:

  • 我猜messages 为空。
  • 您的消息对象或其中的一条消息为空。
  • @Matthijs 这不是messages。当源为空时,LINQ 扩展抛出 ArgumentNullException,而不是 NullReferenceException。可能是列表中的一项。
  • @ahruss:有道理,因为他试图从消息中的每个对象中获取属性值。

标签: c# linq list nullreferenceexception


【解决方案1】:

您有 2 个对象,即您的消息,我假设它是您已初始化的某种列表/数组,列表中是消息对象。列表中至少有一个消息对象为空,因此当它执行 x.MessageSentDate 时,没有 .MessageSentDate。从而抛出 NullException。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    • 2023-03-08
    • 2015-10-02
    相关资源
    最近更新 更多