sandy
sandy

Reputation: 746

Need to sort a list alphabetically

I need to sort out the following list alphabetically increasing order.

IList<KeyValuePair<long, string>> myList = new List<KeyValuePair<long, string>>()

The list is getting populated after making DB call.

myList = DataAdapter.GetTemplates().ToList();

Tried method:

myList = myList.OrderBy(x => x.Value,StringComparer.OrdinalIgnoreCase).ToList();

However, this doesn't seem to be working correctly. Before sorting:

Assessment1
Assessment2
Assess5
Assess7
Toxic Only
Perform Only
Question only

After sorting:

Assess5
Assess7 
Assessment1
Assessment2
Perform Only
Question only
Toxic Only

Upvotes: 1

Views: 116

Answers (2)

ProgrammingLlama
ProgrammingLlama

Reputation: 38880

Note This answer was posted before OP changed their question. Originally OP wanted to sort all of the items except the first one. Original revision


You could do this using LINQ:

myList = myList
    .Take(1) // take the first item from the list
    .Concat( // concatenate the following subquery
        myList
            .Skip(1) // take all elements after the first one
            .OrderBy(kv => kv.Value, StringComparer.OrdinalIgnoreCase) // sort by the value ignoring the case
    )
    .ToList(); // materialise the query to a list

The current comparer is case insensitive, but you can choose an appropriate one for your use case.

The result for your sample input is as follows:

Assessment1
Assess5
Assess7
Assessment2
Perform Only
Question only
Toxic Only

Try it online

Upvotes: 4

Rahul_Mandhane
Rahul_Mandhane

Reputation: 352

you can use bubble sort, just start the second loop from 1

for (int i = 0; i < n - 1; i++)
            for (int j = 1; j < n - i - 1; j++)
                if (arr[j] > arr[j + 1])
                {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
    }

as shown above, 2nd loop is started with 1, so it will exclude element at the 0th index

Upvotes: 1

Related Questions