[ACCEPTED]-LINQ: Get first character of each string in an array-string

Accepted answer
Score: 25

try this:

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

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

string shortName = new string(someName.Where(s => !string.IsNullOrEmpty(s))
                                      .Select(s => s[0]).ToArray());
Score: 8
  string[] someName = new string[] { "First", "MiddleName", "LastName" };
  String initials = String.Join(".",someName.Select(x => x[0].ToString()).ToArray());

Produces

F.M.L

0

Score: 7

This solution accounts for empty strings 1 as well by removing them from the output

var shortName = new string(
  someName
    .Where( s => !String.IsNullOrEmpty(s))
    .Select(s => s[0])
    .ToArray());
Score: 0
string initials = someName.Where(s => !string.IsNullOrEmpty(s))
                          .Aggregate("", (xs, x) => xs + x.First());

0

More Related questions