【问题标题】:LINQ to XML - avoid duplicate entriesLINQ to XML - 避免重复条目
【发布时间】:2012-03-13 05:13:44
【问题描述】:

XML 结构:

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

我不想通过 linq to 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);
      }

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

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

【问题讨论】:

  • 显示您实际添加员工的代码 - 我只是看到您覆盖了属性
  • 刚刚添加了我实际添加员工的代码
  • 真的看不懂你的foreach循环!您将在循环中添加太多具有相同属性的项目!

标签: c# linq-to-xml


【解决方案1】:

要向您的 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
}

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2012-08-24
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 2014-11-23
      • 1970-01-01
      • 2019-11-16
      • 1970-01-01
      相关资源
      最近更新 更多