简体   繁体   English

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

[英]How to remove items from List of HashSet of int in a loop

I have the following lists: 我有以下列表:

        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},
        };

I want to remove from set the subSet.Count() items, which isProperSubSet, and the result must be: 我想从集合中删除subPro.Sub()项目isProperSubSet,结果必须是:

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

How can I do it? 我该怎么做?

I tried like this, but I get an index error (must be non negative and less then the collection): 我这样尝试过,但出现索引错误(必须为非负数,并且小于集合):

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);
                }

            }
        }

First, you should not remove elements from subSet or the other elements of set which the subset is not a proper subSet won't be removed. 首先,您不应该从subSet删除元素,或者不会删除子集不是适当subSetset的其他元素。

Second, juharr said, you have to add a break inside the if : 其次,juharr说,您必须在if内添加一个中断:

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

        }
    }

Basically you need to break out of the inner loop once you remove a value from set . 基本上,一旦从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;
        }
     }
}

That's because you might still be iterating the inner loop and now your j will actually reference the wrong position (which might be beyond the new length of the list). 那是因为您可能仍在迭代内部循环,现在您的j实际上将引用错误的位置(可能超出列表的新长度)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM