oliverbooth / X10D

Extension methods on crack.
https://oliverbooth.github.io/X10D/
MIT License
28 stars 2 forks source link

[Request]: Method to swap all elements between 2 Lists #62

Closed RealityProgrammer closed 2 years ago

RealityProgrammer commented 2 years ago

Type to extend

System.Collections.Generic.List

Signature

void Swap(List<T> list2)

Summary

Swap all elements between 2 List<T>, mimic C++'s std::vector.swap()

Parameters

Parameter Type Description
list2 List<T> List to receive all items from list1

Benefits

Mimic C++'s std::vector::swap, quick and easy

Drawbacks

O(n) operation, with n is the largest size between 2 lists, unlike C++, std::vector::swap will swap 2 data pointers at constant time

Implementation Example

var min = Math.Min(list1.Count, list2.Count);
for (int i = 0; i < min; i++) {
    (list1[i], list2[i]) = (list2[i], list1[i]);
}

if (list2.Count < list1.Count) {
    list2.EnsureCapacity(list1.Count);
    for (int i = min; i < list1.Count; i++) {
        list2.Add(list1[i]);
    }

    list1.RemoveRange(min, list1.Count - min);
} else if (list1.Count < list2.Count) {
    list1.EnsureCapacity(list2.Count);
    for (int i = min; i < list2.Count; i++) {
        list1.Add(list2[i]);
    }

    list2.RemoveRange(min, list1.Count - min);
}

Code of Conduct

oliverbooth commented 2 years ago

Added with 02765b8b197a3108b25c580035e753545e7f8762, defined for IList<T> rather than List<T>.