>我有以下列表:
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},
};
我想从集合中删除子集.计数()项,即ProperSubSet,结果必须是:
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
实际上将引用错误的位置(可能超出列表的新长度)。
首先,您不应该从subSet
中删除元素,或者子集不是正确subSet
不会删除的set
的其他元素。
其次,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;
}
}
}