在LINQ中检查值是否存在

3

这是我的 XML 文件

<Persons>
  <Person>
    <id>1</id>
    <Name>Ingrid</Name>
  </Person>
  <Person>
    <id>2</id>
    <Name>Ella</Name>
    </Person>
</Persons>

我正在使用 Linq XML。

在这里,ID 应该是自动生成的。

我需要检查节点 ID 的值是否已经存在。

如果不存在,它应该创建一个新的 ID。如何使用 Linq 实现呢?

有什么指针吗?

谢谢。

1个回答

5
    XDocument doc = XDocument.Parse(xml);

    int id = 1;
    // if you need the element
    XElement ingrid = (from person in doc.Root.Elements("Person")
                       where (int)person.Element("id") == id
                       select person).FirstOrDefault();
    // if you just need to know if it is there
    bool exists = (from person in doc.Root.Elements("Person")
                       where (int)person.Element("id") == id
                       select person).Any();
    // generate a new ID
    int newId = ((from person in doc.Root.Elements("Person")
                  select (int?)person.Element("id")).Max() ?? 0) + 1;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接