这是在重构园子博客后台多级分类的实现代码时遇到的一个问题
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);
}
请问最简单的方法是什么?
选用了 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);
}
刚想说个更简单的:
currentDescendantIds = currentDescendantIds.Union(branchDescendantIds);
Union方法本身就是IEnumrerable<T>的扩展方法,只要是子类型为IEnumerable<T>的都可以直接用,我没有理解力为什么要判断类型
@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: 明白了,当开发人员使用HashSet类型来创建该对象时,应该是数据量很大的场景,你这里判断HashSet就用Hashset的高性能方法,如果不是HashSet,就意味着传入的值量不会很大,就直接用接口扩展方法,你根据数据类型来判断开发者的意图,我理解应该没错,棒棒的!
currentDescendantIds = currentDescendantIds.AddRange(branchDescendantIds).Distinct();