首页 新闻 会员 周边 捐助

C# 中给一个列表中添加另外一个列表时自动去重的最简单方法

1
悬赏园豆:30 [已解决问题] 解决于 2025-07-07 16:26

这是在重构园子博客后台多级分类的实现代码时遇到的一个问题

TreeCategoryDto 的定义

public class TreeCategoryDto : TreeNode<TreeCategoryDto>
{
    public int CategoryId { get; set; }

    public string Title { get; set; }

    public int ItemCount { get; set; }

    public int ChildCount => Children?.Count ?? 0;

    public IEnumerable<int> DescendantIds { get; set; } = new List<int>();
}

给 DescendantIds 添加 branchDescendantIds,希望在添加时自动去重,用 List 的 AddRange 方法不会去重

if (current.DescendantIds is List<int> currentDescendantIds)
{
    currentDescendantIds.AddRange(branchDescendantIds);
}

请问最简单的方法是什么?

问题补充:

不一定用 List<int>,只要支持 IEnumerable<int> 就行

dudu的主页 dudu | 高人七级 | 园豆:25265
提问于:2025-07-07 15:08
< >
分享
最佳答案
1

选用了 HashSet + UnionWith

public class TreeCategoryDto : TreeNode<TreeCategoryDto>
{
    public IEnumerable<int> DescendantIds { get; set; } = new HashSet<int>();
}
if (current.DescendantIds is HashSet<int> currentDescendantIds)
{
    currentDescendantIds.UnionWith(branchDescendantIds);
}
dudu | 高人七级 |园豆:25265 | 2025-07-07 16:26

刚想说个更简单的:
currentDescendantIds = currentDescendantIds.Union(branchDescendantIds);
Union方法本身就是IEnumrerable<T>的扩展方法,只要是子类型为IEnumerable<T>的都可以直接用,我没有理解力为什么要判断类型

Tonhuan-Cloud | 园豆:244 (菜鸟二级) | 2025-07-07 16:31

@Tonhuan-Cloud: 用 Union 不需要判断类型,的确更简单,选用 UnionWith 是因为我们想使用 HashSet,通过它确保不出现重复的值,改进后的实现

if (current.DescendantIds is HashSet<int> currentDescendantIds)
{
    currentDescendantIds.UnionWith(branchDescendantIds);
}
else
{
    current.DescendantIds = current.DescendantIds.Union(branchDescendantIds);
}

stackoverflow 上有个 Union vs Unionwith 的性能比较 https://stackoverflow.com/q/45917831

dudu | 园豆:25265 (高人七级) | 2025-07-07 17:09

@dudu: 明白了,当开发人员使用HashSet类型来创建该对象时,应该是数据量很大的场景,你这里判断HashSet就用Hashset的高性能方法,如果不是HashSet,就意味着传入的值量不会很大,就直接用接口扩展方法,你根据数据类型来判断开发者的意图,我理解应该没错,棒棒的!

Tonhuan-Cloud | 园豆:244 (菜鸟二级) | 2025-07-07 17:22
其他回答(1)
1

currentDescendantIds = currentDescendantIds.AddRange(branchDescendantIds).Distinct();

收获园豆:30
Tonhuan-Cloud | 园豆:244 (菜鸟二级) | 2025-07-07 16:17
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册