【问题标题】:If statement selecting only first value in linq2xml query如果语句仅选择 linq2xml 查询中的第一个值
【发布时间】:2020-06-21 12:27:25
【问题描述】:

我有一个正在读取的 XML 文件。我正在尝试检查 Product.Id 是否在 XML 文件中。问题:它只读取第一个 XML Product 值。

我有以下 if 语句:

    if ((int)user.ElementAt(0).Element("Product").Element("Id") == product.Id)
    {
       // Do some logic
    }

用户选择如下所示:

    var user = from item in doc.Descendants("User")
               where (string)item.Element("Username") == username
               select item.Element("UserProducts");

此 XML 中的选择结果:

<UserProducts>
  <Product>
    <Id>1</Id>
    <Name>Mouse</Name>
    <Amount>2</Amount>
  </Product>
  <Product>
    <Id>2</Id>
    <Name>Keyboard</Name>
    <Amount>1</Amount>
  </Product>
</UserProducts>

if 语句只检查第一个 Product 条目(ID 1、Name Mouse、Amount 2)。它不检查第二个条目。

为什么它不检查第二个条目,我该如何解决它以便检查所有条目?

预期输出: 一个 if 语句,它检查所有产品条目,而不仅仅是第一个条目。

【问题讨论】:

  • linq 名称必须与 xml 匹配。从:用户更改为:产品。然后从:用户名更改为:名称,最后选择项目
  • @jdweng 我认为问题中发布的 Xml 是 user 查询而不是原始 xml 的结果

标签: c# xml linq linq-to-xml


【解决方案1】:

select item.Element("UserProducts") 之后添加.ToList() 并检查foreach 循环中的条件

【讨论】:

  • 我的 IDE 中出现“'XElement' 不包含 'ToList' 的定义”错误。
  • 你用过using System.Linq;吗?
  • 是的。我认为问题在于我没有创建一个新对象(使用 select new Object 语句),所以它不能列出查询?
猜你喜欢
  • 2011-01-03
  • 2021-08-04
  • 1970-01-01
  • 2022-01-09
  • 2015-08-03
  • 2015-11-05
  • 1970-01-01
  • 2022-01-10
  • 2012-11-15
相关资源
最近更新 更多