I need to convert list of strings which contains one long string where values are separated with ,
and \n
. Example:
string[] namesArray = {"Name1,Surname1", "Name2,Surname2", "Name3,Surname3"};`
string nameSting = "";
foreach(string nameFromArray in namesArray) {
nameSting = nameFromArray "\n";
}
List<string> namesList = new List<string>();
namesList.Add(nameSting);
My question is how can I process namesList
so Console.WriteLine
outputs the following format:
1. Name1 Surname1
2. Name2 Surname2
3. Name3 Surname3
Please note that nothing above can be changed. I know it's a weird code but it's a very simplified way to show how API returns data which needs to be converted in the format described above.
CodePudding user response:
The following
string[] namesArray = {"Name1,Surname1", "Name2,Surname2", "Name3,Surname3"};
int index = 1;
namesArray.ToList().ForEach(n => {Console.WriteLine(index ". " n.Replace(',', ' ')); index ;});
will output:
1. Name1 Surname1
2. Name2 Surname2
3. Name3 Surname3
Don't forget to include the following using statements:
using System.Linq;
using System.Collections.Generic;
CodePudding user response:
Split by new line and then split by comma
var names = namesList
.SelectMany(t => t.Split(new string[] { Environment.NewLine }, StringSplitOptions.None))
.Select(name => name.Split(','))
.Select((name, index) => (Index: index, FirstName: name[0], Surname: name[1]));
foreach(var name in names)
{
Console.WriteLine($"{name.Index}. {name.FirstName} {name.Surname}");
}