简体   繁体   English

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

[英]Sorting a list based on string case

How can I sort a List by order of case eg 如何按案例顺序对列表进行排序,例如

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

I would like to sort so that the upper case record is first in the list eg SMTP:user@anotherdomain.com. 我想排序,以便大写记录在列表中排在第一位,例如SMTP:user@anotherdomain.com。

You can use StringComparer.Ordinal to get a case sensitive sorting: 您可以使用StringComparer.Ordinal来获取区分大小写的排序:

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

        l.Sort(StringComparer.Ordinal);

I was writing another example while t4rzsan has answered =) I prefer t4rzsan´s answer... anyway, this is the answer I was writing. 我写了另一个例子,而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
    }
}

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

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. 在您的情况下,默认排序功能可能会起作用。

您需要创建一个实现IComparer的自定义比较器类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM