Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Sorting Strings only on first letter

I'm trying to sort a list of strings in alphabetical order in C#. My code looks like this:

public static List<Result> sort(List<Result> listToSort)
{
    int listSize = listToSort.Count;
    for (int i = 0; i < listSize; i++)
    {
       for (int j = 0; j < listSize; j++)
       {
           if (listToSort[i].SN[0] < listToSort[j].SN[0])
           { 
               Result tempValue = listToSort[j];
               listToSort[j] = listToSort[i];
               listToSort[i] = tempValue;
            }
        }
    }

    return listToSort;
}

But it's only sorting it based on the first letter of a string. In other words, if I have a list like this:

donald, abby, dave, bob, sam, pete

It will sort it like so:

abby, bob, donald, dave, pete, sam

One would expect 'dave' to come before 'donald'.. Any ideas?


2 Answers

Currently you are only sorting by the first letter that is why you are seeing this result. You can use Enumerable.OrderBy - LINQ

List<Result> sortedList = listToSort.OrderBy(r=> r.SN).ToList();

Or for your current code you can modify your check to:

if (string.Compare(listToSort[i].SN,listToSort[j].SN) < 0)
like image 155
Habib Avatar answered Nov 23 '25 03:11

Habib


How about using LINQ for this:

return listToSort.OrderBy(report => report.SN)

I'm assuming your Report class has a string property you want the list to be sorted by?

EDIT

Didn't notice that you'd already specified the SN property, have amended my answer.

like image 34
Paul Aldred-Bann Avatar answered Nov 23 '25 01:11

Paul Aldred-Bann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!