如何对IEnumerable <string>进行排序

Cat*_*lla 90 .net c# sorting string ienumerable

我怎样才能IEnumerable<string>按字母顺序排序.这可能吗?

编辑:我如何编写就地解决方案?

dtb*_*dtb 145

你可以用任何其他可枚举的方式进行排序:

var result = myEnumerable.OrderBy(s => s);
Run Code Online (Sandbox Code Playgroud)

要么

var result = from s in myEnumerable
             orderby s
             select s;
Run Code Online (Sandbox Code Playgroud)

或(忽略大小写)

var result = myEnumerable.OrderBy(s => s,
                                  StringComparer.CurrentCultureIgnoreCase);
Run Code Online (Sandbox Code Playgroud)

请注意,与LINQ一样,这会创建一个新的IEnumerable <T>,当枚举时,它会按排序顺序返回原始IEnumerable <T>的元素.它不会对IEnumerable <T>进行就地排序.


IEnumerable <T>是只读的,也就是说,您只能从中检索元素,但不能直接修改它.如果要对就地字符串集合进行排序,则需要对实现IEnumerable <string>的原始集合进行排序,或者首先将IEnumerable <string>转换为可排序的集合:

List<string> myList = myEnumerable.ToList();
myList.Sort();
Run Code Online (Sandbox Code Playgroud)

根据您的评论:

_components = (from c in xml.Descendants("component")
               let value = (string)c
               orderby value
               select value
              )
              .Distinct()
              .ToList();
Run Code Online (Sandbox Code Playgroud)

要么

_components = xml.Descendants("component")
                 .Select(c => (string)c)
                 .Distinct()
                 .OrderBy(v => v)
                 .ToList();
Run Code Online (Sandbox Code Playgroud)

或者(如果你想稍后在列表中添加更多项目并保持排序)

_components = xml.Descendants("component")
                 .Select(c => (string)c)
                 .Distinct()
                 .ToList();

_components.Add("foo");
_components.Sort();
Run Code Online (Sandbox Code Playgroud)

  • `OrderBy`返回`IOrderedEnumerable <T>`.`IOrderedEnumerable <T>`派生自`IEnumerable <T>`因此它可以像`IEnumerable <T>`一样使用,但它扩展了类型,例如,允许使用`ThenBy`. (2认同)

Jam*_*ran 10

这是不可能的,但事实并非如此.

基本上,任何排序方法都会将你复制IEnumerable到a List,排序List然后返回给你排序列表,这也是IEnumerable一个IList.

这意味着你失去了一个"继续无限"的属性IEnumerable,但是无论如何你也无法对它进行排序.

  • 对吧.IEnumerable的目的是通过继续询问"下一个"项目,向您展示一系列句柄,您可以从头开始结束迭代.这意味着可以在知道所有内容之前部分迭代IEnumerable; 你不必知道你什么时候经历过它们,直到你有.排序(就像Linq允许你做的许多事情一样)需要整个系列的知识作为有序列表; 在排序系列中首先出现的项目可能是系列返回的最后一项,除非您知道所有项目是什么,否则您不会知道. (7认同)

Lar*_*nal 8

myEnumerable = myEnumerable.OrderBy(s => s);
Run Code Online (Sandbox Code Playgroud)