C# sorting strings small and capital letters

前端 未结 2 1855
攒了一身酷
攒了一身酷 2021-01-19 19:07

Is there a standard functionality which will allow me to sort capital and small letters in the following way or I should implement a custom comparator:

stude         


        
相关标签:
2条回答
  • 2021-01-19 19:46

    I believe you want to group those strings which starts with lower case and upper case, then sort them separately.

    You can do:

    list = list.Where(r => char.IsLower(r[0])).OrderBy(r => r)
          .Concat(list.Where(r => char.IsUpper(r[0])).OrderBy(r => r)).ToList();
    

    First select those string which starts with lower case, sort them, then concatenate it with those strings which start with upper case(sort them). So your code will be:

    List<string> list = new List<string>();
    list.Add("student");
    list.Add("students");
    list.Add("Student");
    list.Add("Students");
    list = list.Where(r => char.IsLower(r[0])).OrderBy(r => r)
          .Concat(list.Where(r => char.IsUpper(r[0])).OrderBy(r => r)).ToList();
    for (int i = 0; i < list.Count; i++)
        Console.WriteLine(list[i]);
    

    and output:

    student
    students
    Student
    Students
    
    0 讨论(0)
  • 2021-01-19 19:49

    Do you mean something on these lines

    List<string> sort = new List<string>() { "student", "Students", "students", 
                                             "Student" };
    List<string> custsort=sort.OrderByDescending(st => st[0]).ThenBy(s => s.Length)
                                                             .ToList();
    

    The first one orders it by the first character and then by the length. It matches the output you suggested by then as per the pattern i mentioned above else you will do some custom comparer

    0 讨论(0)
提交回复
热议问题