【问题标题】:Select unique XElements (by attribute) with a filter using LinqToXml使用 LinqToXml 使用过滤器选择唯一的 XElement(按属性)
【发布时间】:2008-12-05 20:28:49
【问题描述】:

我有一个类似下面的 XML 文档:

<items>
 <item cat="1" owner="14">bla</item>
 <item cat="1" owner="9">bla</item>
 <item cat="1" owner="14">bla</item>
 <item cat="2" owner="12">bla</item>
 <item cat="2" owner="12">bla</item>
</items>

现在我想使用 linq 查询获取属于指定类别的所有唯一所有者(我实际上只需要所有者的属性值)。在我的示例中,对 cat 1 的查询将返回一个包含 9 和 14 的列表。我该怎么做? Linq 语法比 Lambda 更受欢迎。在此先感谢 ;)

【问题讨论】:

    标签: c# xml linq-to-xml unique


    【解决方案1】:

    假设片段在 itemsElement 中:

    var distinctOwners = (from item in itemsElement.Element("item") 
     where itemElements.Attribute("cat") == 1 
    select item.Attribute("owner")).Distinct();
    

    对格式和缩进表示歉意!

    【讨论】:

    • 或 'lambda' 形式: itemElements .Where(x=>x.Attribute("cat")==1) .Select(x=>x.Attribute("owner")) 。清楚的();我个人更喜欢那个!
    • 'itemElements' 应该是 where 子句中的 'item'。 Attribute 方法返回一个不能与 1 比较的 XAttribute 使用 == 需要强制转换为 int 并且 Distinct for cat="2" 仍将返回 2 个项目,因为这两个属性都是一个不同的对象。
    • ...所以除了明显的语法错误和我完全缺乏 xlinq 知识之外,我在金钱上是有竞争力的。想知道是否有任何方法可以对您自己的帖子投反对票...
    【解决方案2】:

    试试这个功能:-

    static IEnumerable<int> GetOwners(XDocument doc, string cat)
    {
        return from item in doc.Descendants("item")
            where item.Attribute("cat").Value == cat
            select (int)item.Attribute("owner")).Distinct();
    
    }
    

    【讨论】:

      【解决方案3】:
        XElement ele = XElement.Parse(@"<items><item cat=""1"" owner=""14"">bla</item><item cat=""1"" owner=""9"">bla</item>" +
                                      @"<item cat=""1"" owner=""14"">bla</item><item cat=""2"" owner=""12"">bla</item>" +
                                      @"<item cat=""2"" owner=""12"">bla</item></items>");
      
        int cat = 1;
      
      
        List<int> owners = ele.Elements("item")
          .Where(x=>x.Attribute("cat").Value==cat.ToString()).Select(x=>Convert.ToInt32(x.Attribute("owner").Value)).Distinct().ToList();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-24
        相关资源
        最近更新 更多