如何在循环中从int的HashSet列表中删除项目

露西安·布姆(Lucian Bumb)

我有以下列表:

        var set = new List<HashSet<int>>()
        {
            new HashSet<int>() { 1,2,3,4},
            new HashSet<int>() { 1,2,3,5},
            new HashSet<int>() { 1,2,4,5},
            new HashSet<int>() {2,3,4,5}
        };

        var subSet = new List<HashSet<int>>()
        {
            new HashSet<int>() { 1,2,3},
            new HashSet<int>() { 1,2,4},
        };

我想从集合中删除subPro.Sub()项目isProperSubSet,其结果必须是:

        var result= new List<HashSet<int>>()
        {
            new HashSet<int>() { 1,2,3,5},             
            new HashSet<int>() {2,3,4,5}
        };

我该怎么做?

我这样尝试过,但出现索引错误(必须为非负且小于集合):

for(int j=set.Count-1;j-->0;)
        {
            for (int i = subSet.Count-1;i-->0;)
            {
                if (subSet[i].IsProperSubsetOf(set[j]))
                {
                    subSet.RemoveAt(i);
                    set.RemoveAt(j);
                }

            }
        }
朱哈尔

基本上,一旦您从中删除了一个值,就需要打破内部循环set

for(int j=set.Count-1; j >= 0; j--)
{
    for (int i = subSet.Count-1; i >= 0; i--)
    {
        if (subSet[i].IsProperSubsetOf(set[j]))
        {
            subSet.RemoveAt(i);
            set.RemoveAt(j);
            break;
        }
     }
}

那是因为您可能仍在迭代内部循环,现在您j实际上将引用错误的位置(可能超出列表的新长度)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章