简体   繁体   English

Linq 表达式未按预期工作

[英]Linq expression not working as expected

I want to select some values from a collection of strings, I wrote it one using LINQ and one using a foreach statement.我想从一组字符串中选择一些值,我使用 LINQ 编写了一个值,使用foreach语句编写了一个值。

With the foreach version I get a list of about 300 entries.对于foreach版本,我得到了大约 300 个条目的列表。

List<string> res = new List<String>();
foreach (var l in anchors)
{
      if (l.Attributes["href"] != null)
      {
          res.Add(l.Attributes["href"].Value);
      }
}

With the LINQ version I get null :使用 LINQ 版本我得到null

IEnumerable<string> res2 = anchors.Select(l => l?.Attributes["href"]?.Value);

With the linq, you're getting null values as well and adding it to your enumerable.使用 linq,您还将获得空值并将其添加到您的可枚举中。 It's not identical to your foreach.它与您的 foreach 不同。 Change it to:将其更改为:

IList<string> res2 = anchors.Where(l=>l.Attributes["href"] != null).Select(l => l.Attributes["href"].Value).ToList();

The .? .? syntax returns null if the item it is applied to returns null .如果应用它的项目返回null语法返回null In this case, null is added to the output.在这种情况下,将向输出添加null

With the check if (l.Attributes["href"] != null) it is not added to the output.通过检查if (l.Attributes["href"] != null)它不会被添加到输出中。

To mimic that in LINQ, add a Where clause.要在 LINQ 中模仿,请添加Where子句。

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

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