首页 > 解决方案 > linq:对 xml 中的重复节点进行分组、排序和删除

问题描述

我有这样的菜单xml:

<root>
    <item name="submenu" href="">
        <item name="delete post" href="example.com/delete" />
        **<item name="delete post" href="" />**
        **<item name="add post" href="" />**
        <item name="add post" href="example.com/add" />
        **<item name="add post" href="" />**
        <item name="do not remove" href="" />        
    </item>
    <item name="list post" href="example.com/list" />
    **<item name="list post" href="" />**
    <item name="remove only one of these" href="" />
    **<item name="remove only one of these" href="" />**
</root>

我需要删除重复项并在此处找到解决方案: 在 c# 中有效删除重复的 xml 元素

我的问题是如果有href填充我想保留这个确切的记录 - 所以我需要在分组之后但在删除记录之前对它们进行排序。

所以我需要删除标记为**但无法使OrderBy(string.IsNullOrWhiteSpace)​​用GroupBy.

任何帮助表示赞赏。

标签: c#xmllinqlinq-to-xml

解决方案


这是你要找的吗?

public class Item
{
    public string Name { get; set; }
    public string Href { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var data = new List<Item>
        {
            new Item { Name="1", Href="" },
            new Item { Name="1", Href="b" },
            new Item { Name="2", Href="c" },
            new Item { Name="2", Href="" },
            new Item { Name="2", Href="" },
        };

        var results = data.OrderBy(d => d.Name).ThenByDescending(d => d.Href).GroupBy(d => d.Name).Select(g => g.First());

        foreach (var result in results)
        {
            Console.WriteLine(result.Name + ", " + result.Href);
        }

        Console.ReadLine();
    }
}

结果是:

1、乙

2、丙


推荐阅读