3 回答
TA贡献1891条经验 获得超3个赞
作为替代方案,如果您不想实现全新的自定义订单方法,您可以创建扩展方法并使用现有的订单方法:
public static class MyExtensions
{
public static IEnumerable<string> OrderByCyrillicFirst(this IEnumerable<string> list)
{
var cyrillicOrderedList = list.Where(l => string.IsNullOrEmpty(l) ? false : IsCyrillic(l[0])).OrderBy(l => l);
var latinOrderedList = list.Where(l => string.IsNullOrEmpty(l) ? true : !IsCyrillic(l[0])).OrderBy(l => l);
return cyrillicOrderedList.Concat(latinOrderedList);
}
public static IEnumerable<string> OrderByCyrillicFirstDescending(this IEnumerable<string> list)
{
var cyrillicOrderedList = list.Where(l => string.IsNullOrEmpty(l) ? false : IsCyrillic(l[0])).OrderByDescending(l => l);
var latinOrderedList = list.Where(l => string.IsNullOrEmpty(l) ? true : !IsCyrillic(l[0])).OrderByDescending(l => l);
return cyrillicOrderedList.Concat(latinOrderedList);
}
//cyrillic symbols start with code 1024 and end with 1273.
private static bool IsCyrillic(char ch) =>
ch >= 1024 && ch <= 1273;
}
和用法:
var listExample = new List<string>(){ "banana", "apple", "lemon", "orange", "cherry", "pear", "яблоко", "лимон", "груша", "банан", "апельсин", "вишня" };
var result = listExample.OrderByCyrillicFirst();
输出:
апельсин банан вишня груша лимон яблоко 苹果香蕉樱桃柠檬橙梨
TA贡献1780条经验 获得超5个赞
对于相当“快速和肮脏”的方法,我可能会按“包含西里尔字母的第一个索引”(int.MaxValue用于“无西里尔字母”)进行排序,然后是常规排序(允许您使其不区分大小写等)。
所以像:
var result = list.OrderBy(GetFirstCyrillicIndex).ThenBy(x => x).ToList();
...
private static int GetFirstCyrillicIndex(string text)
{
// This could be written using LINQ, but it's probably simpler this way.
for (int i = 0; i < text.Length; i++)
{
if (text[i] >= 0x400 && text[i] <= 0x4ff)
{
return i;
}
}
return int.MaxValue;
}
完整的例子,包括我尴尬的话:
using System;
using System.Collections.Generic;
using System.Linq;
class Test
{
static void Main()
{
var list = new List<string> {
"banana", "apple", "lemon", "orange",
"cherry", "pear", "яблоко", "лимон",
"груша", "банан", "апельсин", "вишня",
"appleвишня", "вишняapple"
};
var result = list.OrderBy(GetFirstCyrillicIndex).ThenBy(x => x).ToList();
foreach (var item in result)
{
Console.WriteLine(item);
}
}
private static int GetFirstCyrillicIndex(string text)
{
// This could be written using LINQ, but it's probably simpler this way.
for (int i = 0; i < text.Length; i++)
{
if (text[i] >= 0x400 && text[i] <= 0x4ff)
{
return i;
}
}
return int.MaxValue;
}
}
结果:
апельсин
банан
вишня
вишняapple
груша
лимон
яблоко
appleвишня
apple
banana
cherry
lemon
orange
pear
- 3 回答
- 0 关注
- 167 浏览
添加回答
举报