使用不同拆分从字符串创建多个列表

Mat*_*nis 0 c# visual-studio

这是示例代码.

我有串行星的名字,它们的顺序和颜色,通过分开spacesNewLines.

我不想修改字符串来改变结果.


我想创建3个列表Order,NameColor从字符串中创建.

| Order      | Name       | Color      |
|------------|------------|------------|
| First      | Mercury    | Gray       |
| Second     | Venus      | Yellow     |
| Third      | Earth      | Blue       |
| Fourth     | Mars       | Red        |
Run Code Online (Sandbox Code Playgroud)

这将创建一个List来自string,拆分NewLine.

string planets = "First Mercury Gray" 
                + Environment.NewLine 
                + "Second Venus Yellow"
                + Environment.NewLine
                + "Third Earth Blue"
                + Environment.NewLine 
                + "Fourth Mars Red"
                + Environment.NewLine;


List<string> PlanetOrder = planets.Split(
               new[] { Environment.NewLine }, StringSplitOptions.None).ToList();   

List<string> PlanetName = planets.Split(
               new[] { Environment.NewLine }, StringSplitOptions.None).ToList();

List<string> PlanetColor = planets.Split(
               new[] { Environment.NewLine }, StringSplitOptions.None).ToList();
Run Code Online (Sandbox Code Playgroud)

但是在每一行中我怎样才能拆分space并选择单词[1]Order,[2]Name,[3]Color?

planets.Split(' ')[2]; //Name
Run Code Online (Sandbox Code Playgroud)

Ben*_*Ben 6

您可以执行以下操作.首先拆分字符串Environment.NewLine,然后拆分结果的每一行,space并将项目添加到不同的列表.

string planets = "First Mercury Gray"
            + Environment.NewLine
            + "Second Venus Yellow"
            + Environment.NewLine
            + "Third Earth Blue"
            + Environment.NewLine
            + "Fourth Mars Red"
            + Environment.NewLine;

List<string> PlanetOrder = new List<string>();
List<string> PlanetName = new List<string>();
List<string> PlanetColor = new List<string>();
string[] lines = planets.Split(new string[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
    string[] arr = line.Split(' ');
    PlanetOrder.Add(arr[0]);
    PlanetName.Add(arr[1]);
    PlanetColor.Add(arr[2]);
}
Run Code Online (Sandbox Code Playgroud)