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 關注
- 199 瀏覽
添加回答
舉報