tags:

views:

274

answers:

4

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

I would like to sort so that the upper case record is first in the list e.g SMTP:[email protected].

A: 

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.

DasBoot
A: 

you need to create a custom comparer class that implements IComparer

ob
+7  A: 

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);
Jakob Christensen
That is great, thanks a lot.
+1  A: 

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:[email protected]");
        MyList.Add("smtp:[email protected]");
        MyList.Add("SMTP:[email protected]");

        MyList.Sort(new MyStringComparer());

        foreach (string s in MyList)
        {
            Console.WriteLine(s);
        }

        Console.ReadLine();
    }
}
Javier Morillo