Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting strings in C#

Tags:

c#

sorting

I have a delimited string that I need sorted. First I need to check if 'Francais' is in the string, if so, it goes first, then 'Anglais' is next, if it exists. After that, everything else is alphabetical. Can anyone help me? Here's what I have so far, without the sorting

private string SortFrench(string langs)
    {
       string _frenchLangs = String.Empty;
       string retval = String.Empty;

        _frenchLangs = string.Join(" ; ",langs.Split(';').Select(s => s.Trim()).ToArray());

        if (_frenchLangs.Contains("Francais"))
            retval += "Francais";

        if (_frenchLangs.Contains("Anglais"))
        {
            if (retval.Length > 0)
                retval += " ; ";

            retval += "Anglais";
        }

        //sort the rest

        return retval;
    }
like image 419
Mark Highfield Avatar asked Nov 27 '22 17:11

Mark Highfield


1 Answers

Someone liked my comment, so figured I'd go ahead and convert that into your code:

private string SortFrench(string langs)
{
    var sorted          = langs.Split(';')
        .Select(s => s.Trim())
        .OrderByDescending( s => s == "Francais" )
        .ThenByDescending( s => s == "Anglais" )
        .ThenBy ( s => s )
        .ToArray();

    return string.Join(" ; ",sorted);
}

My syntax may be off slightly as I've been in the Unix world for awhile now and haven't used much LINQ lately, but hope it helps.

like image 168
Kevin Nelson Avatar answered Dec 15 '22 15:12

Kevin Nelson