【问题标题】:Linq: no return value caused exceptionLinq:没有返回值导致异常
【发布时间】:2017-09-06 22:58:44
【问题描述】:

我有这个查询 LINQ 来抓取网页

string temp = statusLinkList[0].Descendants()
    .Where(x => (x.Name == "a" && x.Attributes["title"].Value.Contains("Go to the first page of results.")))
    .ToList()
    .First()
    .GetAttributeValue("href", null);

在某些情况下,查询不会返回任何记录,这会导致异常。在这种情况下,我需要设置默认值。最合适的是使用“.DefaultIfEmpty()”。我无法实现这一点以避免异常并设置字符串 temp 的默认值。

string temp = statusLinkList[0].Descendants()
    .Where(x => (x.Name == "a" && x.Attributes["title"].Value.Contains("Go to the first page of results.")))
    .DefaultIfEmpty()
    .ToList()
    .First()
    .GetAttributeValue("href", null);

此处返回空列表“.ToList().First()。”

我现在谷歌过度了。在此先感谢您对此事的任何帮助。

【问题讨论】:

  • 我很不清楚你所说的“我无法实现这个来避免异常并设置默认值 od string temp”是什么意思。
  • (也不清楚为什么要创建一个完整的列表只是为了获得第一个值。ToList 调用的意义何在?)
  • 如果只关心第一个,不要先.ToList(),也试试.FirstOrDefault()?.Get...
  • 使用 FirstOrDefault() 并包含在 try/catch 中以帮助进一步调试问题。如果它在 for 循环中保留重写功能以更好地查看碎片。
  • @crashmstr 谢谢你指出我的愚蠢代码。它帮助我更多地了解 LINQ。

标签: c# linq


【解决方案1】:

首先,删除查询中的ToList。它无缘无故地在内存中创建一个临时列表。 其次,DefaultIfEmpty 允许在没有被Where 过滤的匹配项的情况下传递回退值。那么First 是安全的。

string hrefFallback = null;

string temp = statusLinkList[0].Descendants()
    .Where(x => x.Name == "a" && x.Attributes["title"].Value.Contains("Go to the first page of results."))
    .Select(x => x.GetAttributeValue("href", hrefFallback))
    .DefaultIfEmpty(hrefFallback)
    .First();

【讨论】:

  • 非常感谢,这正是我要找的。​​span>
【解决方案2】:

您需要检查空列表。我会去:

var node statusLinkList[0].Descendants().Where(
    x => (x.Name == "a" && x.Attributes["title"].Value.Contains("Go to the first page of results."))).Single();
if (node!=null)
{
    string temp = node.GetAttributeValue("href", null);
}

前提是只有一个“转到结果的第一页”。

【讨论】:

  • 感谢您的代码,但我想避免使用 if 语句。
  • @Petr Minarik:很好。那么你应该接受 Tim Schmelter 的回答。
猜你喜欢
  • 2010-10-09
  • 1970-01-01
  • 2010-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-16
  • 1970-01-01
相关资源
最近更新 更多