English 中文(简体)
LINQ 回收无效结果
原标题:LINQ query returning null results

I have the following code

nodes = data.Descendants(XName.Get("{http://schemas.microsoft.com/LiveSearch/2008/04/XML/web}Results")).Nodes();
        System.Collections.Generic.IEnumerable<Result> res = new List<Result>();
        if (nodes.Count() > 0)
        {
            var results = from uris in nodes
                          select new Result
        {
            URL =
((XElement)uris).Element(XName.Get("{http://schemas.microsoft.com/LiveSearch/2008/04/XML/web}Url")).Value,
            Title =
((XElement)uris).Element(XName.Get("{http://schemas.microsoft.com/LiveSearch/2008/04/XML/web}Title")).Value,
            Description =
((XElement)uris).Element(XName.Get("{http://schemas.microsoft.com/LiveSearch/2008/04/XML/web}Description")).Value,
            DateTime =
((XElement)uris).Element(XName.Get("{http://schemas.microsoft.com/LiveSearch/2008/04/XML/web}DateTime")).Value,
        };
            res = results;
        }

Where Results is a object who has those URL, Title, Description, and DateTime variables defined.

This all works fine normally, but when a node in nodes doesnt contain a Description element (or at least I think thats whats throwing it) the program hits the "res = results;" line of code and throws a object reference not set to... error and highlights the whole section right after "select new Results"..

我如何确定这一点?

最佳回答

最为简单的办法是投到<条码>,其中载明,而不是使用<条码>。 这样,你就用<代码>null查询<代码>代替>。

但是,你的法典也可成为>>>>nicer:

XNamespace ns = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/web";

var results = data.Descendants(ns + "Results")
                  .Elements()
                  .Select(x => new Result 
                          {
                            URL = (string) x.Element(ns + "Url"),
                            Title = (string) x.Element(ns + "Title"),
                            Description = (string) x.Element(ns + "Description"),
                            DateTime = (string) x.Element(ns + "DateTime")
                          })
                  .ToList();

参看更简单些什么? 所用的技术:

  • Calling ToList() on an empty sequence gives you a list anyway
  • This way you ll only ever perform the query once; before you were calling Count() which would potentially have iterated over each node. In general, use Any() instead of Count() > 0) - but this time just making the list unconditional is simpler.
  • Use the Elements() method to get child elements, rather than casting multiple times. (Your previous code would have thrown an exception if it had encountered any non-element nodes)
  • Use the implicit conversion from string to XNamespace
  • Use the +(XNamespace, string) operator to get an XName
问题回答

如果该说明内容没有列入,请加以测试。

((XElement)uris).Element(XName.Get("{http://schemas.microsoft.com/LiveSearch/2008/04/XML/web}Description"))

在使用价值之前,不作废。 该法典:

var results = from uris in nodes let des = ((XElement)uris).Element(XName.Get("{http://schemas.microsoft.com/LiveSearch/2008/04/XML/web}Description"))
                      select new Result
    {
        URL = ((XElement)uris).Element(XName.Get("{http://schemas.microsoft.com/LiveSearch/2008/04/XML/web}Url")).Value,
        Title = ((XElement)uris).Element(XName.Get("{http://schemas.microsoft.com/LiveSearch/2008/04/XML/web}Title")).Value,
        Description = (des != null) ? des.Value : string.Empty,
        DateTime = ((XElement)uris).Element(XName.Get("{http://schemas.microsoft.com/LiveSearch/2008/04/XML/web}DateTime")).Value,
    };




相关问题
LINQ to SQL and a running total on ordered results

I want to display a customer s accounting history in a DataGridView and I want to have a column that displays the running total for their balance. The old way I did this was by getting the data, ...

Can I do this with an IQueryable<T>?

is it possible to add an extension method to IQueryable<T> and then, for my Linq2Sql or EF or NHibernate or LinqToObjects, define it s functionality / how each repository will impliment this ...

AlphaNumeric ordering in SQL vs. LINQ and .NET

I encountered an interesting thing today that I have never noticed before. It appears that SQL and LINQ order AlphaNumeric strings differently. Data table contains rows: A G 6 P 1 D J 2 T Z 9 F 0 ...

If statement or Where extension with a For Each loop?

I was wondering which of the two code samples would be more efficient (or is the difference between the two negligible)? For Each apple in AppleController.GetRedApples().Where(Function(a) ...

Differences between LINQ to Objects and LINQ to SQL queries

I have been using LINQ to query my POCO objects for some time, but I have not yet tried LINQ to SQL. I assume that LINQ to SQL queries are somehow converted to equivalent SQL queries and, given this, ...

动态准则 询问

能否在业余时间建立LinqQuries。

热门标签