Standing on the shoulders of giants. RSS 2.0
# Monday, April 07, 2008
class Program {
    static void Main(string[] args) {

        string[] strings = { "aa", "bb", "c", "dddd", "eeee", "f" };

        // use a class which implements IComparer
        // This works best when you want to re-use sorting logic
        //  or need to store state between using the comparer.
        Array.Sort(strings, new StringLengthComparer());

        // The following two methods only differ in syntax, both use a delegate.

        // use an anonymous method
        Array.Sort(strings, delegate(string x, string y) { return x.Length - y.Length; });

        // use a lambda expression
        Array.Sort(strings, (x, y) => x.Length - y.Length);

    }

    class StringLengthComparer : IComparer<string> {

        public int Compare(string x, string y) {
            return x.Length - y.Length;
        }
    }
}

Note: The array is sorted on the length of the strings, if you want to sort the strings in the array based on the content use an instance of the StringComparer class.

Monday, April 07, 2008 9:42:29 AM (W. Europe Daylight Time, UTC+02:00)  #    Comments [0] - Trackback
C# | Codesnippet
Comments are closed.
About
© Copyright 2009
Paul van Brenk
Sign In
newtelligence dasBlog 2.3.8275.16006
All Content © 2009, Paul van Brenk
DasBlog theme 'Business' created by Christoph De Baene (delarou)