newUser
newUser

Reputation:

Swap List<> elements with c# using LINQ

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

Upvotes: 8

Views: 14240

Answers (3)

Andrew Siemer
Andrew Siemer

Reputation: 10278

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;
            }
        }   
    }

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564383

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);

Upvotes: 17

Matthew Groves
Matthew Groves

Reputation: 26096

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.

Upvotes: 2

Related Questions