C# - 如何按从小到大的顺序重新排列新的 HashSet<int>

C# - How to rearrange new HashSet<int> by order of least to greatest

我先道歉,但我不确定如何准确地表达这个问题。

我有一段代码目前运行良好,它的唯一目的是查找唯一标识符的所有组合。这很好用,但我想做的是创建一个真正使组合独一无二的迭代。

我的意思是下面,你会看到一段简单的代码。将 HashSet 添加到列表中。然后你会看到一个创建新哈希集列表的方法。我知道如果我可以在每个 HashSet 中订购什么,那么它将使自己独一无二。

static void Main(string[] args)
    {

        List<HashSet<int>> myInts = new List<HashSet<int>>();
        myInts.Add(new HashSet<int>{1, 2});
        myInts.Add(new HashSet<int>{2, 1});
    }

   private static List<HashSet<int>> RemoveDuplicates(List<HashSet<int>> hash)
    {
        List<HashSet<int>> returnSet = new List<HashSet<int>>();
        for (int i = 0; i < hash.Count; i++)
        {
           //do the order here and add it to the return set

        }


        return returnSet;

    }

所以代码是正确的,1,2 与 2,1 不同,但是在我的对象中它们是相同的组合。所以我的流程是,如果我可以对数组进行排序,那么 HashSet 将使它独一无二,因为两者都是 1,2

您不需要订购商品,您可以使用 SetEquals 来检查集合是否包含相同的元素。

private static List<HashSet<int>> RemoveDuplicates(List<HashSet<int>> hash)
{
    List<HashSet<int>> returnSet = new List<HashSet<int>>();
    for (int i = 0; i < hash.Count; i++)
    {
        var isDupe = false;
        //do the order here and add it to the return set
        for (int j = i + 1; j < hash.Count; j++)
        {
            if(hash[i].SetEquals(hash[j]))
            {
                isDupe = true;
                break;
            }
        }
        if (!isDupe)
        {
            returnSet.Add(hash[i]);
        }
    }
    return returnSet;
}

虽然这是相当昂贵的,假设 SetEquals 是 O(n) 并且你有 k 个集合,那将是 O(n*k2)