根据字符串大小写对列表进行排序

时间:2009-02-19 20:12:06

标签: c# sorting list

如何按案例顺序对列表进行排序,例如

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

我想排序,以便大写记录在列表中排在第一位,例如SMTP:user@anotherdomain.com。

4 个答案:

答案 0 :(得分:12)

您可以使用StringComparer.Ordinal获取区分大小写的排序:

        List<string> l = new List<string>();
        l.Add("smtp:a");
        l.Add("smtp:c");
        l.Add("SMTP:b");

        l.Sort(StringComparer.Ordinal);

答案 1 :(得分:1)

我正在写另一个例子,而t4rzsan已回答=)我更喜欢t4rzsan的答案......无论如何,这是我写的答案。

//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
    }
}

使用自己的字符串比较器的示例:

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

答案 2 :(得分:0)

大多数语言库都有内置的排序功能,可以指定比较功能。您可以自定义比较功能,以根据您想要的任何条件进行排序。

在您的情况下,默认排序功能可能会起作用。

答案 3 :(得分:0)

您需要创建一个实现IComparer

的自定义比较器类