Firoso Firoso - 2 months ago 6
C# Question

How do I sort a string array alphabetically by length?

By alphabetically by length I mean as follows:

given:
{ "=", "==>>", "=>>", "=>", "!>" }

I want to get out:

!>
=
=>
=>>
==>>


I'm currently just using OrderBy(x => x.Length).ToArray()

anyone got a better lambda?

Is this reasonably possible? lol, I'm not sure what the rule conventions here would be :-(

Answer

Writing your own string comparer you can do this, which meets both set of requirements you've posted.

    public class MyStringComparer : IComparer<string>
    {
        #region IComparer<string> Members

        public int Compare(string x, string y)
        {
            if (x[0] == y[0])
            {
                return x.Length.CompareTo(y.Length);
            }
            else return x[0].CompareTo(y[0]);
        }

        #endregion
    }

a bcde bcd b bced cb

would yield:

a b bcd bcde bced cb

and { "=", "==>>", "=>>", "=>", "!>" }

yields:

!>
=
=>
=>>
==>>

by calling: myStringCollection.OrderBy(x=>x, new MyStringComparer).ToArray();

Comments