How do I clone a generic list in C#?

前端 未结 26 2479
失恋的感觉
失恋的感觉 2020-11-22 01:27

I have a generic list of objects in C#, and wish to clone the list. The items within the list are cloneable, but there doesn\'t seem to be an option to do list.Clone()

26条回答
  •  北海茫月
    2020-11-22 01:55

    The following code should transfer onto a list with minimal changes.

    Basically it works by inserting a new random number from a greater range with each successive loop. If there exist numbers already that are the same or higher than it, shift those random numbers up one so they transfer into the new larger range of random indexes.

    // Example Usage
    int[] indexes = getRandomUniqueIndexArray(selectFrom.Length, toSet.Length);
    
    for(int i = 0; i < toSet.Length; i++)
        toSet[i] = selectFrom[indexes[i]];
    
    
    private int[] getRandomUniqueIndexArray(int length, int count)
    {
        if(count > length || count < 1 || length < 1)
            return new int[0];
    
        int[] toReturn = new int[count];
        if(count == length)
        {
            for(int i = 0; i < toReturn.Length; i++) toReturn[i] = i;
            return toReturn;
        }
    
        Random r = new Random();
        int startPos = count - 1;
        for(int i = startPos; i >= 0; i--)
        {
            int index = r.Next(length - i);
            for(int j = startPos; j > i; j--)
                if(toReturn[j] >= index)
                    toReturn[j]++;
            toReturn[i] = index;
        }
    
        return toReturn;
    }
    

提交回复
热议问题