开发者

check value exists in linq

开发者 https://www.devze.com 2023-01-08 21:57 出处:网络
this is my xml file <Persons> <Person> <id>1</id> <Name>Ingrid</Name>

this is my xml file

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

i am using linq xml.

here the id should be auto-generated..

i need to check if the value of node id already exists .

if not exists it should create a new id..how to do this using linq. any pointers?

th开发者_StackOverflowank you


    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;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号