按字母顺序对集合进行排序
我们在谈什么样的收藏? A List<T>
? ICollection<T>
?阵列?集合中存储的类型是什么?
假设List<string>
,你可以这样做:
List<string> str = new List<string>();
// add strings to str
str.Sort(StringComparer.CurrentCulture);
重构! (还有5个去..) – 2010-08-16 16:24:10
我不喜欢在一般情况下使用'var' – thecoop 2010-08-16 16:25:23
@thecoop除非上下文不容易看到,否则var是真棒 – sparkyShorts 2017-06-08 20:34:37
List<string> stringList = new List<string>(theCollection);
stringList.Sort();
List<string>
实现ICollection<string>
,所以你仍然有所有你转换到一个列表即使集合为中心的功能。
Array.Sort怎么样?即使您没有提供自定义比较,默认情况下它会按字母顺序排列:
var array = new string[] { "d", "b" };
Array.Sort(array); // b, d
这可能不是现成的,但你也可以使用LinqBridge http://www.albahari.com/nutshell/linqbridge.aspx做LINQ查询在2.0(Visual Studio 2008是推荐虽然)。
查看http://stackoverflow.com/questions/188141/c-list-orderby-alphabetical-order – 2010-08-16 16:01:15
@多米尼克这个问题是关于3.5,这意味着Linq。 – Will 2010-08-16 16:03:01
@Dominic:我看到Q和大多数A使用C#3 – 2010-08-16 16:03:06