4

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?

5 Answers 5

26

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());
Sign up to request clarification or add additional context in comments.

1 Comment

If any of the strings are empty, this will throw
8
  string[] someName = new string[] { "First", "MiddleName", "LastName" };
  String initials = String.Join(".",someName.Select(x => x[0].ToString()).ToArray());

Produces

F.M.L

Comments

7

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

1 Comment

that wont compile, you forgot ToArray()
0
string initials = someName.Where(s => !string.IsNullOrEmpty(s))
                          .Aggregate("", (xs, x) => xs + x.First());

4 Comments

Bonus points for using Aggregate instead of String.Join or a string constructor.
I dunno if thats bonus points worthy, its kind of overkill at this point :P
Overkill perhaps, but Aggregate (aka reduce of map/reduce) is a useful thing to know about LINQ.
Your creating a new string with every + operation so thats way less efficient than the above solutions.
-3
string[] someName = new string[] { "First", "MiddleName", "LastName" };

someName.FirstOrDefault();

1 Comment

i think you misunderstood the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.