如何排序一个IEnumerable&LT;字符串&GT; [英] How to sort an IEnumerable<string>
问题描述
我如何排序的的IEnumerable&LT;字符串&GT;
字母顺序排列。这可能吗?
How can I sort an IEnumerable<string>
alphabetically. Is this possible?
编辑:如何将我写的就地解决方案
How would I write an in-place solution?
推荐答案
同样的方式,你会来排序任何其他枚举:
The same way you'd sort any other enumerable:
var result = myEnumerable.OrderBy(s => s);
或
var result = from s in myEnumerable
orderby s
select s;
或(不区分大小写)
or (ignoring case)
var result = myEnumerable.OrderBy(s => s,
StringComparer.CurrentCultureIgnoreCase);
需要注意的是,像通常那样使用LINQ,这将创建一个新的IEnumerable&LT; T&GT;其中,枚举时,返回原始的IEnumerable&LT的元素; T&GT;按照排序顺序。它不排序的IEnumerable&LT; T&GT;原地。
Note that, as is usual with LINQ, this creates a new IEnumerable<T> which, when enumerated, returns the elements of the original IEnumerable<T> in sorted order. It does not sort the IEnumerable<T> in-place.
将IEnumerable&LT; T&GT;是只读,也就是说,你只能检索从它的元素,但不能直接对其进行修改。如果你想就地字符串的集合进行排序,你需要排序的原始集合其实现IEnumerable&LT;字符串&gt;中,或把一个IEnumerable&LT;字符串&GT;成可排序的集合第一:
An IEnumerable<T> is read-only, that is, you can only retrieve the elements from it, but cannot modify it directly. If you want to sort a collection of strings in-place, you need to sort the original collection which implements IEnumerable<string>, or turn an IEnumerable<string> into a sortable collection first:
List<string> myList = myEnumerable.ToList();
myList.Sort();
根据您的评论:
Based on your comment:
_components = (from c in xml.Descendants("component")
let value = (string)c
orderby value
select value
)
.Distinct()
.ToList();
或
_components = xml.Descendants("component")
.Select(c => (string)c)
.Distinct()
.OrderBy(v => v)
.ToList();
或者(如果您想在以后添加更多的项目到列表中,并保持它排序)
or (if you want to later add more items to the list and keep it sorted)
_components = xml.Descendants("component")
.Select(c => (string)c)
.Distinct()
.ToList();
_components.Add("foo");
_components.Sort();
这篇关于如何排序一个IEnumerable&LT;字符串&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!