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.

2

4 Answers 4

2

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

var temp = strlist[1];
strlist[1] = strlist[3];
strlist[3] = temp;
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

Try this:

Use a swapping variable

String app = strlist[1];
strlist[1] = strlist[3];
strlist[3] = app;

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.