p.campbell
p.campbell

Reputation: 100567

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?

Upvotes: 4

Views: 22454

Answers (5)

Chirag
Chirag

Reputation: 1

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

someName.FirstOrDefault();

Upvotes: -3

JaredPar
JaredPar

Reputation: 754725

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

var shortName = new string(
  someName
    .Where( s => !String.IsNullOrEmpty(s))
    .Select(s => s[0])
    .ToArray());

Upvotes: 7

Botz3000
Botz3000

Reputation: 39610

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());

Upvotes: 26

Joe Chung
Joe Chung

Reputation: 12123

string initials = someName.Where(s => !string.IsNullOrEmpty(s))
                          .Aggregate("", (xs, x) => xs + x.First());

Upvotes: 0

Stan R.
Stan R.

Reputation: 16065

  string[] someName = new string[] { "First", "MiddleName", "LastName" };
  String initials = String.Join(".",someName.Select(x => x[0].ToString()).ToArray());

Produces

F.M.L

Upvotes: 8

Related Questions