Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: Get first character of each string in an array

Consider a string array shaped like this:

  string[] someName = new string[] { "First", "MiddleName", "LastName" };

The requirement is to get the first character from each element in the array.

i.e.

FML

Previously have tried:

string initials = string.Concat(someName.Select(x => x[0]));

Question: What LINQ query would you write to concatenate all the name contained in the string array to give the initials?

like image 459
p.campbell Avatar asked Nov 28 '22 00:11

p.campbell


1 Answers

try this:

string shortName = new string(someName.Select(s => s[0]).ToArray());

or, if you suspect that any of the strings might be empty or so:

string shortName = new string(someName.Where(s => !string.IsNullOrEmpty(s))
                                      .Select(s => s[0]).ToArray());
like image 131
Botz3000 Avatar answered Dec 18 '22 07:12

Botz3000