我想要一个像 OrderBy()
这样的方法,它总是命令忽略重音字母并将它们视为非重音字母。我已经尝试覆盖 OrderBy()
但似乎我不能这样做,因为那是一个静态方法。
现在我想为 OrderBy()
创建一个自定义的 lambda 表达式,如下所示:
public static IOrderedEnumerable<TSource> ToOrderBy<TSource, TKey>(
this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
if(source == null)
return null;
var seenKeys = new HashSet<TKey>();
var culture = new CultureInfo("pt-PT");
return source.OrderBy(element => seenKeys.Add(keySelector(element)),
StringComparer.Create(culture, false));
}
但是,我收到了这个错误:
Error 2 The type arguments for method 'System.Linq.Enumerable.OrderBy<TSource,TKey>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,TKey>, System.Collections.Generic.IComparer<TKey>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
它似乎不喜欢 StringComparer
。我该如何解决这个问题?
注意:
我已经尝试使用 here 中的 RemoveDiacritics()
但我不知道在这种情况下如何使用该方法。所以我试着做类似 this 的事情这看起来也不错。
最佳答案
OrderBy
需要 keySelector
作为第一个参数。这keySelector
应该是 Func<string,T>
.因此,您需要一个方法,该方法接受一个字符串并返回一个值,您的枚举应按该值进行排序。
不幸的是,我不确定如何确定一个字符是否是“重音字母”。 RemoveDiacritics
不适用于我的 é
.
那么让我们假设您有一个名为 IsAccentedLetter
的方法确定字符是否为重音字母:
public bool IsAccentedLetter(char c)
{
// I'm afraid this does NOT really do the job
return CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.NonSpacingMark;
}
所以你可以这样排序你的列表:
string[] myStrings = getStrings(); // whereever your strings come from
var ordered = myStrings.OrderBy(s => new string(s.Select(c =>
IsAccentedLetter(c) ? ' ' : c).ToArray()), StringComparer.Create(culture, false));
lambda 表达式接受一个字符串并返回相同的字符串,但用空格替换了重音字母。
OrderBy
现在按这些字符串对您的枚举进行排序,因此“忽略”重音字母。
更新:如果您有工作方法 RemoveDiacritics(string s)
返回带有重音字母替换的字符串,您可以简单地调用 OrderBy
像这样:
string[] mystrings = getStrings();
var ordered = myStrings.OrderBy(RemoveDiacritics, StringComparer.Create(culture, false));
关于c# - OrderBy 忽略重音字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35061496/