LINQ to XML - 避免重复条目

时间:2012-03-12 20:48:04

标签: c# linq-to-xml

XML结构:

<Emp>
<Employee username="John"/>      
<Employee username="Jason"/>
</Emp>

我不想通过跟随linq到xml查询将重复的属性插入xml文件

   var newEmployee= XElement.Parse(defaultEmployee.ToString());
   var q = from p in doc.Descendants("Employee")
                        let attr = p.Attribute("username")
                        where attr != null && attr.Value != txtusername.Text 
                        select p;



     foreach(var dupes in q)
      {
         newEmployee.Attribute("username").Value = txtusername.Text ;
         doc.root.Add(newEmployee);
         doc.save(EmployeeFile);
      }

我正在尝试添加一个没有重复项的新员工,但我的代码仍然添加了重复项。

有人可以查看我的查询并让我知道我在哪里错过逻辑吗?

2 个答案:

答案 0 :(得分:2)

要向xml中添加新员工,不需要循环,也不需要解析任何默认XML,只需:

doc.Root.Add(new XElement("Employee", 
                          new XAttribute("username", txtusername.Text));

我不清楚您的循环是什么,目前您选择的是具有不同用户名的任何员工,以及每个您添加新员工节点的员工 - 这不会很有道理,我怀疑你只想添加新员工一次。

如果您想检查具有给定用户名的员工是否已存在:

bool userExistsAlready = doc.Descendants("Employee")
                            .Any(x=> (string)x.Attribute("username") ==  txtusername.Text);

现在,您可以检查添加新员工的代码:

if(!userExistsAlready)
{
  //add new user
}

答案 1 :(得分:1)

使用此LINQ查询,您可以循环用户名属性,提供DISTINCT操作:

    var q = (from p in newEmployee.Descendants("Employee").Attributes("username")
            select (string)p).Distinct();
相关问题