Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

c# - Sorting a List of Strings numerically (1,2,...,9,10 instead of 1,10,2)

I have a List like this:

var l = new List<string> {"bla 1.txt","bla 2.txt","bla 10.txt","bla 3.txt"};

If i call l.Sort(), the list gets sorted in the order 1,10,2,3 which makes sense from a pure string point of view, but sucks from a User Perspective.

Since I don't want to/can't force my users to name them 01, 02, 03,... I wonder if there is either a built-in method or simple algorithm to detect and sort numbers properly, so that I have 1,2,3,10? Since the numbers are only 1 or 2 characters long (i.e., no more than 99) I could possibly do a regex that temporarily prefixes all 1-digit numbers with a 0 and sort, but before I reinvent the wheel I wonder if something already exists?

.net 3.5SP1 if that matters, not 4.0

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The best approach is making use of IComparer. This has already been done and can be found on code project.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...