+-
C#-LINQ中存在检查值
这是我的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执行此操作.
有指针吗?

谢谢

最佳答案
    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;
点击查看更多相关文章

转载注明原文:C#-LINQ中存在检查值 - 乐贴网