【问题标题】:LINQ .ToList() fails on single resultLINQ .ToList() 在单个结果上失败
【发布时间】:2011-01-22 01:51:45
【问题描述】:

可能是星期五晚上很晚,我想回家,或者更可能是我看不到问题......

我有闲置的 LINQ 代码:

mthumbs = itm.Elements(nsr + "thumbnail") != null ? 
      (from mt in itm.Elements(nsr + "thumbnail")
       select new MediaThumbnail
       {
         mediaThumbnailUrl = (string)mt.Attribute("url") ?? null,
         mediaThumbnailHeight = (string)mt.Attribute("height") ?? null,
         mediaThumbnailWidth = (string)mt.Attribute("width") ?? null,
         mediaThumbnailTime = (string)mt.Attribute("time").Value ?? null
        }).ToList() : null

MediaThumbnail 类如下所示:

public class MediaThumbnail
{
    public string mediaThumbnailUrl { get; set; }
    public string mediaThumbnailWidth { get; set; }
    public string mediaThumbnailHeight { get; set; }
    public string mediaThumbnailTime { get; set; }
}

并位于 MediaOptElement 类中,如下所示:

public class MediaOptElement
{
    public string mediaPlayer { get; set; }
    public string mediaRating { get; set; }
    public string mediaRatingScheme { get; set; }
    public string mediaTitle { get; set; }
    public string mediaTitleType { get; set; }
    public string mediaDescription { get; set; }
    public string mediaDescriptionType { get; set; }
    public string mediaKeywords { get; set; }
    public List<MediaThumbnail> mthumbs { get; set; }
    public string mediaCategory { get; set; }
    public string mediaCategoryScheme { get; set; }
    public string mediaCategoryLabel { get; set; }
    public string mediaHash { get; set; }
    public string mediaHashAlgorithm { get; set; }
    public string mediaCopyRights { get; set; }
    public string mediaCopyrightsUrl { get; set; }
    public string mediaRestrictions { get; set; }
    public string mediaRestrictionsRelation { get; set; }
    public string mediaRestrictionsType { get; set; }
    public List<MediaCredit> mediaCredit { get; set; }
}

一些示例 XML:

   <?xml version="1.0" encoding="UTF-8" ?> 
   <rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/">
      <channel>
        <title>wdbj7.com - Sports</title> 
        <link>http://www.wdbj7.com/sports/?track=rss</link> 
        <description>Headlines from wdbj7.com</description> 
        <language>en</language> 
        <copyright>©2011, wdbj7.com</copyright> 
        <lastBuildDate>Fri, 21 Jan 2011 10:47:00 -0500</lastBuildDate> 
        <item>
          <title>Brookville improves to 15-0</title> 
          <link>http://www.wdbj7.com/sports/wdbj7-brookville-improves-to-150-01212011,0,675989.story?track=rss</link> 
          <description><p>The Brookville girls&apos; basketball team graduated two college basketball players last year. That was the last time they lost anything.</p> <p>The Lady Bees are 14-0 on the young season and looked to add to that mark Thursday night against Seminole district rival Liberty.</p> <p>The Minettes playing at home, had just three wins on the year.&nbsp; Haley Comer gets two for the home team. Liberty takes the 2-0 lead.&nbsp; That is when it becomes the Katie Deacon show.</p> <p>The four-year varsity player starts it with the defense.&nbsp; She gets the steal on one end and a basket on the other.</p> <p>Deacon takes her game behind the three point arc!&nbsp; That beats the buzzer at the end of the first quarter!</p> <p>Deacon still not done.&nbsp; She gets another steal and feeds George Mason signee Talisha Watts.<br /><br />Brookville improves to 15-0 with the 57-34 win. <br /><br /></p></description> 
          <pubDate>Fri, 21 Jan 2011 10:47:00 -0500</pubDate> 
          <media:thumbnail url="http://media.trb.com/media/thumbnails/story/2011-01/276990840-21074740.jpg" /> 
          <media:content url="http://media.trb.com/media/alternatethumbnails/story/2011-01/276990840-21074739.jpg" /> 
       </item>
     </channel>
  </rss>

当我运行我的代码时,我收到以下错误:

   Object reference not set to an instance of an object.

堆栈跟踪是:

   at RssAggregator.Reader.RssReader.<>c__DisplayClass7d.<parseFeed>b__6e(XElement mt) in E:\Aggregator\VersionControl\FeedsParserLINQ\RssAggregator\Reader \RssReader.cs:line 843
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at RssAggregator.Reader.RssReader.<>c__DisplayClass7d.<parseFeed>b__57(XElement itm) in E:\Aggregator\VersionControl\FeedsParserLINQ\RssAggregator\Reader\RssReader.cs:line 667
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at RssAggregator.Reader.RssReader.parseFeed(XDocument xmlDoc) in E:\Aggregator\VersionControl\FeedsParserLINQ\RssAggregator\Reader\RssReader.cs:line 666

我可能是错的,但我认为问题发生在 LINQ 查询仅返回一个结果时。但是,我需要能够处理可能只有一个 media:thumbnail 节点或许多 media:thumbnail 节点的情况。有任何想法吗?!谢谢!

【问题讨论】:

  • 你能显示异常本身以及堆栈跟踪的其余部分吗?
  • 附带说明,这段代码中有一堆毫无意义的检查。 Elements() 永远不是 null(它可以返回一个空序列,但这仍然是一个对象)。而a ?? null形式的任何表达式都是无意义的,因为它等价于“如果a不为null则返回a,否则返回null”,与“返回a”相同。
  • 我对此感到困惑:(string)mt.Attribute("url") ?? null。在这里使用合并运算符?? 不是多余的吗?这不是说,“除非它为空,否则使用它;否则,使用空”?
  • 帕维尔,我知道?? null 是多余的,我把它放在那里,所以当我回顾代码时,我可以输入我想要或需要的默认值。
  • 宾果游戏。请参阅下面的答案。您的元素之一没有“时间”属性。

标签: c# xml linq parsing rss


【解决方案1】:

我认为问题出在这一行:

mediaThumbnailTime = (string)mt.Attribute("time").Value ?? null

如果该属性不存在,那么当您尝试使用Value 属性时,您将得到一个NullReferenceException。请注意,在您的示例中,time 属性不存在。

试试这个:

...
using System.Linq;
using System.Xml.Linq;

var mthumbs = itm.Elements( nsr + "thumbnail" )
                 .Select( e => new MediaThumbnail
                  {
                     mediaThumbnailUrl = string.Format( "{0}", e.Attribute("url" ),
                     mediaThumbnailHeight = string.Format( "{0}",e.Attribute("height" ),
                     mediaThumbnailWidth = string.Format( "{0}",e.Attribute("width" ),
                     mediaThumbnailTime = string.Format( "{0}", e.Attribute("time" )
                  })
                 .ToList();

【讨论】:

  • tvanfosson,我可以吻你。 :* 这就是问题所在。其中一个深夜错过了简单的错误!感谢您额外的一双眼睛。
  • +1;我喜欢为此使用string.Format 的想法。我想我也将开始这样做。 :)
【解决方案2】:

我会看他的台词:

mediaThumbnailTime = (string)mt.Attribute("time").Value ?? null

我的猜测是mt.Attribute("time") 为空,这就是导致异常的原因。从我们掌握的信息中很难确定。也许是这样的:

mediaThumbnailTime = (mt.Attribute("time") != null ? (string)mt.Attribute("time").Value : null)

【讨论】:

    【解决方案3】:

    您的问题出在以下代码行:

    mediaThumbnailTime = (string)mt.Attribute("time").Value ?? null
    

    请注意,它与其他 3 个不同之处在于您在此处使用 .Value。如果元素没有“时间”属性,则会失败 - 在这种情况下,.Attribute() 将返回 null,并且访问其上的属性会为您提供 NullReferenceException

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多