8

I have this list

var list = new List { 3, 1, 0, 5 };

I want to swap element 0 with 2

output 0, 1, 3, 5

  • Possible duplicate of [Swap two items in List](http://stackoverflow.com/questions/2094239/swap-two-items-in-listt) – QuarK Oct 22 '16 at 18:52

3 Answers3

17

If you just want it sorted, I'd use List.Sort().

If you want to swap, there is no built in method to do this. It'd be easy to write an extension method, though:

static void Swap<T>(this List<T> list, int index1, int index2)
{
     T temp = list[index1];
     list[index1] = list[index2];
     list[index2] = temp;
}

You could then do:

list.Swap(0,2);
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • You beat me! I would still return an IEnumerable. – Daniel A. White Jul 10 '09 at 17:56
  • 2
    You can't access an IEnumerable by index, so your method wouldn't work. You could return an IEnumerable, but it would be potentially unexpected behavior unless you constructed a copy, since you'd be returning the modified collection. Constructing a copy would add overhead. – Reed Copsey Jul 10 '09 at 18:02
  • You can access an IEnumerable by index using Enumerable.ElementAt. – Joe Chung Jul 11 '09 at 10:42
  • @Joe Chung: But that's not "really" using IEnumerable - it's streaming through the enumerable to get the element at a location, which is horribly inefficient. – Reed Copsey Jul 20 '09 at 17:16
  • 1
    @ReedCopsey you should make that an IList extension, then it works for ObservableCollection and the likes as well. – stijn Dec 18 '11 at 11:36
  • @stijn True, if you want to expose it to all `IList` types. This may or may not be desired... – Reed Copsey Dec 18 '11 at 19:27
2

Classic swap is...


int temp = list[0];
list[0] = list[2];
list[2] = temp;

I don't think Linq has any 'swap' functionality if that's what you're looking for.

Matthew Groves
  • 25,181
  • 9
  • 71
  • 121
1

In the case that something is not directly supported ...make it so number 1!

Take a look at the concept of "extension methods". With this you can easily make your list support the concept of Swap() (this applies to any time you want to extend the functionality of a class).

    namespace ExtensionMethods
    {
        //static class
        public static class MyExtensions 
        {
            //static method with the first parameter being the object you are extending 
            //the return type being the type you are extending
            public static List<int> Swap(this List<int> list, 
                int firstIndex, 
                int secondIndex) 

            {
                int temp = list[firstIndex];
                list[firstIndex] = list[secondIndex];
                list[secondIndex] = temp;

                return list;
            }
        }   
    }
Andrew Siemer
  • 10,166
  • 3
  • 41
  • 61