Sunday, April 3, 2011

Sorting a list based on string case

How can I sort a List by order of case e.g.

  • smtp:user@domain.com
  • smtp:user@otherdomain.com
  • SMTP:user@anotherdomain.com

I would like to sort so that the upper case record is first in the list e.g SMTP:user@anotherdomain.com.

From stackoverflow
  • Most language libraries have a built in sort function with a way to specify the compare function. You can customize the compare function to sort based on any criteria you want.

    In your case the default sort function will probably work.

  • you need to create a custom comparer class that implements IComparer

  • You can use StringComparer.Ordinal to get a case sensitive sorting:

            List<string> l = new List<string>();
            l.Add("smtp:a");
            l.Add("smtp:c");
            l.Add("SMTP:b");
    
            l.Sort(StringComparer.Ordinal);
    
  • Hi all,

    I was writing another example while t4rzsan has answered =) I prefer t4rzsan´s answer... anyway, this is the answer I was writing.

    //Like ob says, you could create your custom string comparer
    public class MyStringComparer : IComparer<string>
    {
        public int Compare(string x, string y)
        {
            // Return -1 if string x should be before string y
            // Return  1 if string x should be after string y
            // Return  0 if string x is the same string as y
        }
    }
    

    Example of using your own string comparer:

    public class Program
    {
        static void Main(string[] args)
        {
            List<string> MyList = new List<string>();
    
            MyList.Add("smtp:user@domain.com");
            MyList.Add("smtp:user@otherdomain.com");
            MyList.Add("SMTP:user@anotherdomain.com");
    
            MyList.Sort(new MyStringComparer());
    
            foreach (string s in MyList)
            {
                Console.WriteLine(s);
            }
    
            Console.ReadLine();
        }
    }
    

0 comments:

Post a Comment