c# - 如何对 IEnumerable<string> 进行排序

标签 c# .net string sorting ienumerable

如何对 IEnumerable<string> 进行排序按字母顺序排列。这可能吗?

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

最佳答案

与您对任何其他可枚举对象进行排序的方式相同:

var result = myEnumerable.OrderBy(s => s);

var result = from s in myEnumerable
             orderby s
             select s;

或(忽略大小写)

var result = myEnumerable.OrderBy(s => s,
                                  StringComparer.CurrentCultureIgnoreCase);

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


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

List<string> myList = myEnumerable.ToList();
myList.Sort();

根据您的评论:

_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();

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

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

_components.Add("foo");
_components.Sort();

关于c# - 如何对 IEnumerable<string> 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3630687/

相关文章:

Python 的 re.split() 没有删除所有匹配的字符

java - 字符串数组为完整数字。 ["2", "2"] 到 22,而不是 [2, 2]

c# - ApiController 没有收到我的日期时间?

c# - ViewData 未传递到 ASP.NET Core 2.1 中的布局

c# - 读取带有分隔符的 INI 文件部分到数组

c# - 使用 Reporting Services 将组保持在一页上

c# - 无法将 System.Xml.XmlNode[] 转换为 System.Byte[]

c++ - 使用 boost 字符串库在 visual studio 中获取字符串编译错误

c# - 如果修改了详细实体,为什么 EntityFramework 会更新主从关系中的主实体?

c# - 引用某些 .NET 库的多个版本的程序集