Shawn Wu
Shawn Wu

Reputation: 7

How to sort a List<string> character by character?

Below code;

static void Main(string[] args)
{
    List<string> list = new List<string>();
    list.Add("using System;");
    list.Add("using System.Linq;");
    list.Add("using System.Collections.Generic;");
    Console.WriteLine(RandomPassword());
}

How can I always get the sorting result below?

using System;  
using System.Collections.Generic;  
using System.Linq;  

I had tried

List = List.OrderByDescending(x => x).ToList();

But doesn't work.

Upvotes: 0

Views: 184

Answers (3)

borkovski
borkovski

Reputation: 978

You could implement a custom comparer:

class AssemblyNameComparer : IComparer<string>
    {
        private readonly IComparer<string> _baseComparer;
        public AssemblyNameComparer(IComparer<string> baseComparer)
        {
            _baseComparer = baseComparer;
        }

        public int Compare(string x, string y)
        {
            string xTrimmed = RemoveSemicolon(x);
            string yTrimmed = RemoveSemicolon(y);
            return _baseComparer.Compare(xTrimmed, yTrimmed);
        }

        string RemoveSemicolon(string x)
        {
            return Regex.Replace(x, ";", "");
        }
    }

This will provide sorting based on 'stripped' values, like:

"using System.Collections.Generic"

and call Sort() method:

        list.Sort(new AssemblyNameComparer(StringComparer.CurrentCulture));

Sort is done in-place, there's no need to assign result anywhere.

Upvotes: 0

user1023602
user1023602

Reputation:

The problem is that ; comes after . in the Unicode character set which is used for sorting.

list.OrderBy(x => x)

    using System.Collections.Generic;
    using System.Linq;
    using System;                      <=== ; comes after dot

If you convert all ; characters to ! (which comes before . in Unicode) then strings containing semicolons will move upwards.

list.OrderBy(x => x.Replace(";", "!"))

    using System;                      <=== ! comes before dot
    using System.Collections.Generic;
    using System.Linq;

Upvotes: 0

Diado
Diado

Reputation: 2257

Assuming you want an array at the end, rather than a list, using this should give you a correctly ordered array:

string[] mySortedArray = list.OrderBy(x => x.Replace(";", string.Empty)).ToArray()

If you require a list, based on your original code:

list = list.OrderBy(x => x.Replace(";", string.Empty)).ToList()

There are two things to note here - firstly, unlike your code, this sort is ascending, not descending; secondly, to give you the result you require you need to strip out the semi-colons while sorting, otherwise they will skew the results, causing the item you wish to be first to come last.

As pointed out in the comments though, there are a number of other issues present in the code you posted.

Upvotes: 3

Related Questions