String-based list sorting

How to sort the list in order, for example,

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

I would like to sort so that the uppercase entry is the first in the list, for example SMTP: user@anotherdomain.com.

+3
source share
4 answers

You can use StringComparer.Ordinal to be case sensitive:

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

        l.Sort(StringComparer.Ordinal);
+11
source

I wrote another example while t4rzsan answered =) I prefer the answer t4rzsan ... anyway, this is the answer I'm 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
    }
}

:

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

. , .

In your case, the default sort function will probably work.

0
source

you need to create a custom comparator class that implements IComparer

0
source

Source: https://habr.com/ru/post/1703524/


All Articles