tags:

views:

621

answers:

4

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

+2  A: 

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.

mgroves
A: 

I don't think that's possible in LINQ... or at the very least, it's silly to do it in LINQ.

void Swap(List list, int a, int b)
{
   int temp = list[a];
   list[a] = list[b];
   list[b] = temp;
}
Spencer Ruport
+5  A: 

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
Dang you beat me.
Daniel A. White
You beat me! I would still return an IEnumerable.
Daniel A. White
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
You can access an IEnumerable by index using Enumerable.ElementAt.
Joe Chung
@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
+1  A: 

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