【发布时间】:2019-08-06 14:10:27
【问题描述】:
我目前有一个字符串列表,需要在不考虑以下字符的情况下进行排序('.', ',', '-', '\'')
示例
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();
老实说,我不知道我在做什么。
有没有其他方法可以得到想要的结果?
【问题讨论】:
-
如果您想要可读性,请使用
Regex。如果您想要性能,请编写一个自定义比较方法,该方法对字符串进行操作,就像对数组进行操作一样。 -
“如果你想要可读性,请使用正则表达式”呃……好吧……正则表达式有很多优点,但“可读性”并不是其中之一。