【问题标题】:How to Avoid Adding Duplicated Item To List Of Multiple Layer如何避免将重复项添加到多层列表中
【发布时间】:2018-11-12 02:08:36
【问题描述】:

我有一个名为以下类型的项目列表

public class ABC
(
    string itemName{get;set;}
    int parentID{get;set;}
    List<ABC> Child {get;set;}    
)

所以Class ABC 显示列表项可以有List&lt;ABC&gt; Child,而List&lt;ABC&gt; Child 可以有另一个List&lt;ABC&gt; Child。 这是问题; 如果我想添加 Class ABC 类型的新项目以列出项目,我如何确保它不在项目列表或其内部子列表中,然后将其添加到项目列表或其任何内部子列表中?

最好的问候

【问题讨论】:

    标签: c# asp.net asp.net-mvc linq asp.net-mvc-4


    【解决方案1】:

    使用扩展函数Flatten

    public static IEnumerable<T> Flatten<T>(this IEnumerable<T> e, Func<T, IEnumerable<T>> flattenFn) => e.SelectMany(c => c.Flatten(flattenFn));
    public static IEnumerable<T> Flatten<T>(this T current, Func<T, IEnumerable<T>> childrenFn) {
        var working = new Stack<T>();
        working.Push(current);
    
        while (working.Count > 0) {
            current = working.Pop();
            yield return current;
    
            if (childrenFn(current) != null)
                foreach (var child in childrenFn(current))
                    working.Push(child);
        }
    }
    

    您可以将原来的 ITEMS List 展平,然后检查您的新项目是否不在其中:

    var exists = ITEMS.Flatten(x => x.Child).Select(x => x.itemName).Contains(newItemID);
    

    如果您经常这样做,明智的做法是考虑使用基于哈希的结构,例如 Dictionary,或者如果您有要添加的唯一项目列表,则从扁平化的 ITEMS 创建一个哈希集到加快检查速度。

    【讨论】:

    • 解决方案需要根据我们如何定义重复进行修改。通过引用或属性值。
    • @NetMage 对不起,我不在办公室,当我在办公室并拥有我的电脑时,我会检查这个并回复您的答案。 tnq 响应
    【解决方案2】:

    给类添加一个递归方法,像这样:

    //using System.Linq;
    
    public class ABC
    (
        string itemName{get;set;}
        int parentID{get;set;}
        List<ABC> Child {get;set;}    
    
        public bool AlreadyContains(ABC abc)
        {
            if (Child.Any( a => a.itemName == abc.itemName )) return true;  //Check children
            return Child.Any( a => a.AlreadyContains(abc) );   //Ask children to check their children too
        }
    )
    

    那么你就可以用一行代码检查:

    if (!abc.AlreadyContains(newAbc)) abc.Add(newAbc);
    

    注意:上面的例子假设 abc 实例在它们的 itemNames 相等时是相等的。当然,您可以修改标准,例如abc.Equals(newAbc) 是否已覆盖 Equals(),或者 abc == newAbc 如果您想要引用相等。

    【讨论】:

    • 对不起,我不在办公室,当我在办公室并拥有我的电脑时,我会检查这个并回复您的答案。 tnq 响应
    猜你喜欢
    • 2011-11-11
    • 2013-01-04
    • 2021-05-08
    • 1970-01-01
    • 2014-02-19
    • 2021-10-16
    • 2013-04-08
    • 2017-08-07
    • 1970-01-01
    相关资源
    最近更新 更多