c# - 如何在不尊重某些字符的情况下对列表进行排序?

标签 c# linq sorting

我目前有一个字符串列表,需要在不考虑以下字符('.'、','、'-'、'\'')的情况下进行排序

示例

        var cities = new List<string>()
        {                
            "Aigle ",
            "Bulle",
            "La Chaux-de-Fonds",
            "L'Abbaye",
            "Malleray",            
            "Sierre",
            "S. City",
            "St-Aubin",
            "St-Cergue",
            "St-Gingolph",
            "St-Légier-La Chiesaz",
            "St-Maurice",
            "St-Sulpice",
            "St-Sulpice",
            "Staad"
        };

默认下单

var ordered = cities
  .OrderBy(x => x)
  .ToList();

输出

"Aigle"
"Bulle"
"La Chaux-de-Fonds"
"L'Abbaye"
"Malleray"
"S. City"
"Sierre"
"Staad"
"St-Aubin"
"St-Cergue"
"St-Gingolph"
"St-Légier-La Chiesaz"
"St-Maurice"
"St-Sulpice"
"St-Sulpice"

我想要的输出必须是这样的。

"Aigle "
"Bulle"
"L'Abbaye"
"La Chaux-de-Fonds"
"Malleray"
"S. City"
"Sierre"
"St-Aubin"
"St-Cergue"
"St-Gingolph"
"St-Légier-La Chiesaz"
"St-Maurice"
"St-Sulpice"
"St-Sulpice"
"Staad"

这样做我得到了我想要的输出。

var ordered = cities
  .OrderBy(x => x.Replace(".", " ").Replace("-", " ").Replace("'", " "))
  .ToList();

老实说,我不知道我在做什么是否合适。

有没有其他方法可以得到想要的结果?

最佳答案

也许转型可以帮到你

var ordered = cities
                .Select(city => new { Name = city, NameForOrdering = string.Join(string.Empty, city.Where(c => Char.IsLetterOrDigit(c)).ToArray()) })

                .OrderBy(city => city.NameForOrdering)
                .Select(city => city.Name)
                .ToList();

这可以作为一种快速而肮脏的方式来帮助您克服障碍或测试一些东西,但真正的解决方案是对 OrderBy 使用第二个重载,这需要您的自定义相等性比较-r.

关于c# - 如何在不尊重某些字符的情况下对列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57378024/

相关文章:

c# - C# 中的矩阵/坐标变换

c# - 这个 LINQ 查询什么时候执行?

arrays - 如何将 ArrayFormula 与数组一起使用(聚合后)?

C# - 修改特定于每种类型的数据结构的通用函数

c# - 编译时出现 MonoTouch 错误:System.Boolean System.Type::op_Equality(System.Type,System.Type)

c# - 在非 IEnumerable 类型上使用 lambda 表达式过滤 Windows 日志

c# - Linq PredicateBuilder - 多个 OR

ruby-on-rails - 根据数组对对象列表进行排序 (Rails)

c++ - 将字符串存储到 vector 中

c# - Nest 5.6 - 如何插入已存在 id 的文档?