简体   繁体   English

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

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

I'll apologize upfront but I'm not sure of how to exactly word this question. 我会先向您道歉,但是我不确定如何准确地表达这个问题。

I have a piece of code that works fine currently that it's sole purpose is to find all the combinations of unique identifiers. 我有一段代码目前运行良好,因为它的唯一目的是找到唯一标识符的所有组合。 And that works fine, but what I'm trying to do is create an iteration that will truly make the combinations unique. 效果很好,但是我想做的是创建一个迭代,该迭代将真正使组合变得唯一。

What I mean is below, you'll see a simple piece of code. 我的意思是在下面,您将看到一段简单的代码。 that adds to HashSet to a list. 将添加到HashSet的列表。 And then you'll see a method which created a new Hashset list. 然后,您将看到一个创建新哈希集列表的方法。 I know if I can order whats in each HashSet then it will make itself unique. 我知道是否可以订购每个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;

    }

So the code is correct, 1,2 is different from 2,1 however, in my objects they are the same combination. 所以代码是正确的,1,2与2,1不同,但是,在我的对象中,它们是相同的组合。 So my though process is if I could order the array then the HashSet will make it unique because both will be 1,2 所以我的流程是,如果我可以订购数组,则HashSet将使其唯一,因为两者均为1,2

You don't need to order items, you can use SetEquals to check if the sets contain the same elements. 您不需要订购商品,可以使用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;
}

This is quite expensive though, assuming SetEquals is O(n) and you have k sets, that will be O(n*k 2 ) 不过,这非常昂贵,假设SetEquals为O(n)且您有k个集合,则将为O(n * k 2

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

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