Search code examples
c#lexicographic

Order a List<object> lexicographically using brute force


That's my code...

string text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse quis nisl vitae dolor tempus iaculis at id augue. Nullam metus mauris, viverra vitae tristique sed, pulvinar ac nulla."

List<object> listCarac = new List<object>();
object aux = 0;

text.Replace(" ", "");

for (int i = 0; i < text.Count(); i++)
{
    listCarac.Add(text.Substring(i,1));
}

for (int x = 0; x < listCarac.Count(); x++)
{
    for (int y = x + 1; y < listCarac.Count(); y++)
    {
        if (listCarac[x] > listCarac[y]) // My problem is here
        {
            aux = listCarac[x];
            listCarac[x] = listCarac[y];
            listCarac[y] = aux;
        }
    }
}

My problem is how to compare lexicographically, i guess the if is comparing alphabetically. Thanks.


Solution

  • Your list contains instances of type object which does not implement IComparable and thus you can´t call instance1 < instance2. However as you put only single characters into your list I guess you can use a List<char> instead or even simpler string instead of a list.

    Thus you can now call this:

    listCarac = listCarac.OrderBy(x => x).ToList();
    

    Which will order your characters lexigraphically.

    Furthermore when calling string.Replace the result is returned by the method as strings are immutable. So Within your first loop you use the original content of text instead of the replaced. Use this instead: text = text.Replace(" ", "");

    EDIT: If - as you claim in your comments - you have to use a list of object and all the instances within this list implement IComparable (which char does) you can simply cast the instances to the interface before sorting:

    var result = listCarac.OfType<IComparable>().OrderBy(x => x);