我使用 System.Linq.Dynamic 来订购项目列表。
items = items.AsQueryable().OrderBy("Name ASC");
令我惊讶的是,小写名称在大写名称之后排序,因此返回的项目如下所示。
Ape
Cat
Dog
alligator
ant
beetle
我期望这个订单:
alligator
ant
Ape
beetle
Cat
Dog
有没有办法获得正确的顺序?检查了 OrderBy 的所有方法签名并用谷歌搜索,但什么也没有。
最佳答案
您不需要创建自定义比较器,因为已经有 StringComparer
派生自 IComparer
的类。
words.OrderBy (x => x, StringComparer.OrdinalIgnoreCase)
这样,如果您想使用其他字符串比较方法(例如 StringComparer.InvariantCultureIgnoreCase
),则无需创建不同的 IComparer
实现。
但是,根据您的情况,这可能是可取的。例如,我确实在 LINQPad 中定义了多个扩展方法,例如 OrderBySelfInvariantCultureIgnoreCase
,因为将其与代码完成一起使用比手动键入等效代码更方便:
public static IEnumerable<string> OrderBySelfInvariantCultureIgnoreCase(this IEnumerable<string> source)
{
return source.OrderBy (x => x, StringComparer.InvariantCultureIgnoreCase);
}
关于c# - 如何使用 System.Dynamic.Linq 排序不区分大小写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29379650/