1

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 :-(

5
  • 1
    "Alphabetically by length" doesn't mean anything. You can sort alphabetically, or you can sort by length. Or, you can sort by one and then sort by the other when the first sort says that they're the same. In your example, you seem to be sorting exclusively alphabetically. Commented Jul 2, 2009 at 17:18
  • Can you explain why you want that result? Why would "!>" be before "=" eventhough it's longer? Commented Jul 2, 2009 at 17:25
  • Is what you really want, to sort alphabetically on the first character and then by length thereafter? Commented Jul 2, 2009 at 17:32
  • Just out of curiosity, what's the application of this code? Commented Jul 3, 2009 at 14:42
  • @Josh command line prompts for different access levels, but i'm honestly just writing a "read until response is found" serial communications function. Commented Jul 7, 2009 at 19:42

7 Answers 7

6

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();

Sign up to request clarification or add additional context in comments.

1 Comment

I don't see the point of creating a custom class here when lambda expressions can do the same thing more succinctly, as I demonstrate.
3

If you want to sort by Alpha then by length, use the OrderBy and ThenBy methods:

var strings = new List<string> { "=", "==>>", "=>>", "=>", "!>" };
strings = strings.OrderBy( x => x ).ThenBy( x => x.Length ).ToList();
strings.ForEach( Console.WriteLine );

Comments

1

I am using a list and I have been trying to search online for a solution for this. Nothing that i found worked for me. I decided to create a method that sorts the elements by length. To sort it first by alphabetical order I use a collection sort.

    subfolders.Sort();
    public void SortByLength(List<string> subfolders)
    {
        int l = 0;
        int l2 = 0;
        for (int i = subfolders.Count() - 1; i != 0; i--)
        {
            l = subfolders[i].Length;
            if (i != subfolders.Count() - 1 && l2 < l)
            {
                string folder = subfolders[i + 1];
                subfolders.RemoveAt(i + 1);
                subfolders.Insert(0, folder);
            }
            l2 = l;
        }
    }

Comments

1

You can use following to sort the array. Here I am sorting the array with middle letter. I think this will help.

string[] names = { "Rajeshwar","Raj", "Vijay", "Sunil","Dhiresh","Sonmani" };
names = names.OrderBy(x => x.Substring(x.Length/2,1)).ToArray();

Comments

0

I tried OrderBy(x => x) with the test data that you provided, and that produces exactly the output that you want.

If it's an array that you have from start, you can just use the Array.Sort method:

Array.Sort(data);

Edit:
The above does not apply to the new data that you have put in the question. Awaiting a clarification about the data (as commented to the question).

Comments

0

I'm not totally clear about your question, but it seems you want to sort firstly by string length, then by alphabetical position.

You could try this as a LINQ solution:

vals = vals.OrderBy(str => str.Length).ThenBy(str => str).ToArray();

If you want a (rather more efficient) solution that does not use LINQ (though still makes nice use of lambda expressions), you could try the following:

Array.Sort(vals, (strA, strB) =>
{
    var lengthComp = Comparer<int>.Default.Compare(strA.Length, strB.Length);
    if (lengthComp == 0)
        return string.Compare(strA, strB);
    return lengthComp;
});

Hope that helps.

Comments

-4

Using a standard string compare function for sorting should do exactly that.

strncmp() in C

String.compare() in C++

String.compareTo() in Java

all work for that purpose.

1 Comment

Well done for not only not answering the question but also providing examples in every mainstream C-style language except C#.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.