1

I have a list:

List<string> strlist=new List<string>();
strlist.add("UK");
strlist.add("US");
strlist.add("India");
strlist.add("Australia");

I want to change the index of some elements in the list:

The current index of "US" is 1, I want to replace it with 3 and for "Australia" it should be 1.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
osama_1200
  • 29
  • 9
  • 1
    possible duplicate of [Function for swapping 2 elements in an array doesn't work](http://stackoverflow.com/questions/16500312/function-for-swapping-2-elements-in-an-array-doesnt-work) – Joe Taras Jul 14 '15 at 09:58
  • So you want the list in the order `UK, Australia, India, US`, is that correct? – Matthew Watson Jul 14 '15 at 10:04

4 Answers4

2

If you know the indices already, you can just use 'swap' them:

var temp = strlist[1];
strlist[1] = strlist[3];
strlist[3] = temp;
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
2

It seems to me that you really just want to sort the list.

If so, just do this:

strlist.Sort().

This will work for a plain list of strings, because string defines a suitable comparison operator that Sort() can use.

If you want to keep "UK" at the start of the list and sort the rest of the list, you can do so like this:

strlist.Sort(1, strlist.Count-1, null);

The above line will result in the list being:

UK
Australia
India
US
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
0

Try this:

Use a swapping variable

String app = strlist[1];
strlist[1] = strlist[3];
strlist[3] = app;
Joe Taras
  • 15,166
  • 7
  • 42
  • 55
0

List<string> can be indexed using list[index] = .... That if you want to replace items manually. Otherwise (I'm guessing), if you need to sort the list alphabetically, but leave the "UK" at the top then you need to do sorting:

var list = new List<string> {"UK", "US", "India", "Australia" };
list.Sort((a, b) =>
{
    if (a == "UK")
        return -1;

    if (b == "UK")
        return 1;

    return string.Compare(a, b, StringComparison.CurrentCulture);
});
Dmitri Trofimov
  • 574
  • 2
  • 17