gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:12:38 25 4
gpt4 key购买 nike

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

示例

        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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com