繁体   English   中英

Linq:无返回值引起的异常

[英]Linq: no return value caused exception

我有这个查询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()。”

我现在被谷歌淹没了。 在此先感谢您的帮助。

首先,在查询中删除ToList 它无缘无故地在内存中创建一个临时列表。 其次,如果没有匹配项通过Where过滤,则DefaultIfEmpty允许传递回退值。 那么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();

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

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);
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM