【发布时间】:2014-06-25 17:18:45
【问题描述】:
我正在尝试使用实体框架OrderByDescending 或OrderBy 对一些字符串进行排序
但是有些方法不起作用,我需要使用带有字符串比较器的排序。
这是我的代码:
public class MyStringComparer : IComparer<string>
{
CultureInfo culture = new System.Globalization.CultureInfo("no");
public int Compare(string x, string y)
{
return string.Compare(x, y, true, culture);
}
}
class Program
{
static void Main(string[] args)
{
MyStringComparer comparer = new MyStringComparer();
List<string> name = new List<string> { "åtestå", "aaabc", "åtestå", "Basxas","xxxax" };
name.OrderByDescending(x => x, comparer);
name.ForEach( x => {
Console.WriteLine(x);
});
Console.ReadKey();
}
}
Comparer 永远不会被调用,我错过了什么?
结果应该是
aaabc
巴斯克萨斯
xxxx
奥斯特奥
åtestå
但它即将到来
奥斯特奥
aaabc
奥斯特奥
巴斯克萨斯
xxxx
如果有其他方法可以做到这一点,请提出建议。
【问题讨论】:
-
EF在哪里使用?
name只是一个例子,DbSet是“真实代码”吗? -
chrfin 的好点子,你不能指望你的自定义比较器在实体框架中工作,因为 SQL 转换会失败。在 SQL Server 中,使用“排序规则”对结果进行排序,默认排序规则由数据库的安装设置,但如果需要可以覆盖。当然,您可以从数据库返回结果并在 .Net 代码中对其进行排序。
标签: c# entity-framework collections