LINQ: get the first character of each line in an array

Consider an array of strings similar to this:

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

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

i.e.

Fml

Previously tried:

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

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

+3
source share
5 answers

try the following:

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

or, if you suspect that any of the lines may be empty or such:

string shortName = new string(someName.Where(s => !string.IsNullOrEmpty(s))
                                      .Select(s => s[0]).ToArray());
+21
source

This solution also considers blank lines, removing them from the output

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

F.M.L

+6
string initials = someName.Where(s => !string.IsNullOrEmpty(s))
                          .Aggregate("", (xs, x) => xs + x.First());
0
string[] someName = new string[] { "First", "MiddleName", "LastName" };

someName.FirstOrDefault();
-2

Source: https://habr.com/ru/post/1716527/


All Articles