【发布时间】:2010-10-08 16:36:42
【问题描述】:
如何按大小写顺序对列表进行排序,例如
- smtp:user@domain.com
- smtp:user@otherdomain.com
- SMTP:user@anotherdomain.com
我想排序,以便大写记录在列表中排在第一位,例如 SMTP:user@anotherdomain.com。
【问题讨论】:
如何按大小写顺序对列表进行排序,例如
我想排序,以便大写记录在列表中排在第一位,例如 SMTP:user@anotherdomain.com。
【问题讨论】:
我正在写另一个例子,而 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();
}
}
【讨论】:
您可以使用 StringComparer.Ordinal 进行区分大小写的排序:
List<string> l = new List<string>();
l.Add("smtp:a");
l.Add("smtp:c");
l.Add("SMTP:b");
l.Sort(StringComparer.Ordinal);
【讨论】:
您需要创建一个实现 IComparer 的自定义比较器类
【讨论】:
大多数语言库都有一个内置的排序函数,可以指定比较函数。您可以自定义比较功能以根据您想要的任何标准进行排序。
在您的情况下,默认排序功能可能会起作用。
【讨论】: