我有一个自定义对象列表,此列表中的一个属性是一个字符串,可以包含整数或整数,然后是一个字符。像这样:
1, 1A, 2, 3, 4, 4B, 4A
如何对此列表进行排序,以便按此排序..
1, 1A, 2, 3, 4, 4A, 4B
我检查了以下链接... Sort array list by numbers then by letters,但只处理一个字符串数组,我的是一个包含多个属性的列表对象。
这是我的自定义对象列表。
var myList = new List<Article>
{
new Article {Position = "1", Info = "test1"},
new Article {Position = "2", Info = "test2"},
new Article {Position = "3", Info = "test3"},
new Article {Position = "4", Info = "test4"},
new Article {Position = "4B", Info = "test5"},
new Article {Position = "4A", Info = "test6"}
};
答案 0 :(得分:0)
我正在使用@MehrzadChehraz in this answer实现的自定义IComparer<T>
(如果这有帮助,请确保给予他信用),并添加缺少的部分,这只是为了使用{{的重载1}}采用自定义Enumerable.OrderBy
:
IComparer<T>
哪个收益率:
答案 1 :(得分:0)
首先,我们可以使用Windows API方法StrCmpLogicalW()
定义&#34;自然排序&#34;的列表扩展名:
public static class ListExt
{
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
private static extern int StrCmpLogicalW(string lhs, string rhs);
// Version for lists of any type.
public static void SortNatural<T>(this List<T> self, Func<T, string> stringSelector)
{
self.Sort((lhs, rhs) => StrCmpLogicalW(stringSelector(lhs), stringSelector(rhs)));
}
// Simpler version for List<string>
public static void SortNatural(this List<string> self)
{
self.Sort(StrCmpLogicalW);
}
}
然后您可以按原样对列表进行排序:
myList.SortNatural(x => x.Position);
注意:您不需要此示例的public static void SortNatural(this List<string> self)
方法,但我将其包含在内以便完整。
答案 2 :(得分:0)
对于Simplicity,您可以将Regex与Linq结合使用:
Regex rgxNumber = new Regex(@"\d+");
Regex rgxCharacters = new Regex("[a-zA-Z]+");
Func<string, int> getNumberPart = str => int.Parse(rgxNumber.Match(str).ToString());
Func<string, string> getCharactersPart = str => rgxCharacters.Match(str).ToString();
var orderd = myList.OrderBy(x => getNumberPart(x.Position))
.ThenBy(x => getCharactersPart(x.Position)).ToList();
这假设没有1B2
形式的数据。