Nin*_*ita 7 c# sorting lambda expression letters
我想要一个像OrderBy()这样的方法总是命令忽略重音字母,并像非重音一样看待它们.我已经尝试覆盖OrderBy()但似乎我不能这样做,因为这是一个静态方法.
所以现在我想创建一个自定义的lambda表达式OrderBy(),如下所示:
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));
}
Run Code Online (Sandbox Code Playgroud)
但是,我收到此错误:
错误2方法'System.Linq.Enumerable.OrderBy <TSource,TKey>的类型参数(System.Collections.Generic.IEnumerable <TSource>,System.Func <TSource,TKey>,System.Collections.Generic.IComparer <TKey >)'无法从使用中推断出来.尝试显式指定类型参数.
似乎它不喜欢StringComparer.我怎么解决这个问题?
注意:
我已经尝试使用RemoveDiacritics()从这里,但我不知道如何使用这种方法在这种情况下.于是,我就做这样的事情这似乎不错了.
解决了!我收到该错误是因为要使用StringComparer该元素在表达式中进行排序,OrderBy()该元素需要是一个string.
因此,当我知道该元素是一个字符串时,我将其转换为字符串,并使用该RemoveDiacritics()方法来忽略带重音的字母并将它们视为非重音的字母。
public static IOrderedEnumerable<TSource> ToOrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
if(!source.SafeAny())
return null;
return source.OrderBy(element => Utils.RemoveDiacritics(keySelector(element).ToString()));
}
Run Code Online (Sandbox Code Playgroud)
为了保证RemoveDiacritics()工作正常,我添加了HtmlDecode()一行。
public static string RemoveDiacritics(string text)
{
if(text != null)
text = WebUtility.HtmlDecode(text);
string formD = text.Normalize(NormalizationForm.FormD);
StringBuilder sb = new StringBuilder();
foreach (char ch in formD)
{
UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(ch);
if (uc != UnicodeCategory.NonSpacingMark)
{
sb.Append(ch);
}
}
return sb.ToString().Normalize(NormalizationForm.FormC);
}
Run Code Online (Sandbox Code Playgroud)