字符串到数组,按第3个字/列排序 [英] String to Array, Sort by 3rd Word/Column
本文介绍了字符串到数组,按第3个字/列排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含数字,单词和换行符的字符串,我将其拆分为一个数组.
I have a string with numbers, words, and linebreaks that I split into an Array.
如果我运行Array.Sort(lines)
,它将按列1 Number
的方式对数组进行数字排序.
If I run Array.Sort(lines)
it will sort the Array numerically by Column 1, Number
.
我该如何改为按列3 Color
的字母顺序对数组进行排序?
How can I instead sort the Array alphabetically by Column 3, Color
?
注意:它们不是真实的列,只是将单词分隔开的空格.
Note: They are not real columns, just spaces separating the words.
我无法修改字符串来更改结果.
I cannot modify the string to change the results.
| Number | Name | Color |
|------------|------------|------------|
| 1 | Mercury | Gray |
| 2 | Venus | Yellow |
| 3 | Earth | Blue |
| 4 | Mars | Red |
C#
示例: http://rextester.com/LSP53065
string planets = "1 Mercury Gray\n"
+ "2 Venus Yellow\n"
+ "3 Earth Blue\n"
+ "4 Mars Red\n";
// Split String into Array by LineBreak
string[] lines = planets.Split(new string[] { "\n" }, StringSplitOptions.None);
// Sort
Array.Sort(lines);
// Result
foreach(var line in lines)
{
Console.WriteLine(line.ToString());
}
所需的排序数组结果
3 Earth Blue
1 Mercury Gray
4 Mars Red
2 Venus Yellow
推荐答案
尝试以下代码:
string planets = "1 Mercury Gray \n"
+ "2 Venus Yellow \n"
+ "3 Earth Blue \n"
+ "4 Mars Red \n";
var lines = planets.Split("\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.OrderBy(s => s.Split(' ')[2])
.ToArray();
foreach (var line in lines)
{
Console.WriteLine(line);
}
谢谢@Kevin!
这篇关于字符串到数组,按第3个字/列排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文