List<string> names = new List<string>() { "John", "Anna", "Monica" };
var result = String.Join("", names.ToArray());
I would like to Join only 1 specific character from each string. Let's say, the 3rd one. Without loop if possible.
// result = "hnn"
CodePudding user response:
To Add to the Linq answers, the simplest one would likely be:
var result = String.Join("", names.Select(x => x[2]).ToArray());
Select simply maps that function over each element.
You can also extract that to a function easily:
public static string TakeNthCharacter(List<string> names, int n) {
return String.Join("", names.Select(x => x[n]).ToArray());
}
CodePudding user response:
You can do this with LINQ:
List<string> names = new List<string>() { "John", "Anna", "Monica" };
var result = String.Join
(
"",
from x in names
select x[2]
);
CodePudding user response:
Hello probably you want something like this:
List<string> names = new List<string>() { "John", "Anna", "Monica" };
const int specificCharacter = 2;
var result = names.Where(name => specificCharacter < name.Length)
.Aggregate(string.Empty, (current, name) => current name[specificCharacter]);
where
is for you do not get a System.IndexOutOfRangeException
And Aggregate
to "join" the string. Here is the link with more information about it.
https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.aggregate?view=net-6.0
CodePudding user response:
All the 3 answers work well. I tried to iterate 300.000 times all 3 of them and the second method works faster (36s against 45s for the first and 49s for the third). Therefore I valid the second answer as the main answer.