linq if语句问题

时间:2011-01-22 17:45:27

标签: c# linq

public IEnumerable<string> References { get; private set; }

References = hrefs.
                Select(href => href.Attributes["href"].Value).
                Distinct().
                ToArray();

我试图让它表现得如果href.Attributes [“onclick”]存在,那么我将onclick值添加到References否则href值。如何检查linq内部?现在我总是添加href值。

编辑:

以及如果类存在如何转到下一个元素并且不添加任何内容。我忘掉了这一点。

2 个答案:

答案 0 :(得分:2)

也许...

References = href
                .Select(href => 
                   href.Attributes["onclick"] != null ? 
                      href.Attributes["onclick"].Value
                    : href.Attributes["href"].Value)
                .Distinct().
                .ToArray();

修改

要回答问题更新,只需添加

即可
.Where(href => href.Attributes["class"] == null)

Select子句之前。

答案 1 :(得分:1)

假设hrefs来自HtmlAgilityPackHtmlNode类型 - 请在您的问题中进行验证。

已修改为class属性添加检查:

References = hrefs
                .Where( href => href.Attributes["class"]==null)
                .Select(href => (href.Attributes["onlick"]!=null) 
                  ? href.Attributes["onlick"].Value
                  : href.Attributes["href"].Value)
                .Distinct()
                .ToArray();