简体   繁体   中英

C# sorting strings small and capital letters

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:

student
students
Student
Students

For an instance:

using System;
using System.Collections.Generic;

namespace Dela.Mono.Examples
{
   public class HelloWorld
   {
      public static void Main(string[] args)
      {
         List<string> list = new List<string>();
         list.Add("student");
         list.Add("students");
         list.Add("Student");
         list.Add("Students");
         list.Sort();

         for (int i=0; i < list.Count; i++)
             Console.WriteLine(list[i]);
      }
   } 
}

it sorts the string as:

student
Student
students
Students

If I try to use list.Sort(StringComparer.Ordinal) , the sorting goes like:

Student
Students
student
students

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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