Introduction
Recently I came across a scenario where I was needed to store only the first character of an input string array. It is easy to do it using loops, however I tried to get the best benefits of lambda expressions which will help write minimal number of lines to achieve this.
Using the code
In this case, I have an input array string and I want to crop everything except the first character from each array element. I am using the Substring
method inside a lambda expression to achieve this. The code is as follows:
string[] input1 = new string[] { "Bharti", "Mangesh", "Akash", "Bhavya", "Chetan" };
string instr = string.Join(",", input1);
string[] output1 = instr.Split(',').Select(a => { var t =
a.Trim().ToUpper().Substring(0, 1); return t; }).ToArray<string>();
Here the string array output1
will store output as shown below:
output1[0]="B"
output1[1]="M"
output1[2]="A"
output1[3]="B"
output1[4]="C"
The above code has limitation that it works in fair cases and does not handle null values. besides we can replace the substring method with first method inside lambda expression which will do the same task.
string input1 = "Bharti, Mangesh,Akash,, Bhavya, Chetan";
string[] instr = input1.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries);
IEnumerable<char> ie = instr.Where(item => item != null).Select(item => item.TrimStart().First());
Here the output enumerable can be converted to char array using ToArray
.
We can achive this result using Loop also which goes like this:
string[] output1 = new string[instr.Length];
for (int i = 0, j = instr.Length; i < j; i++)
{
string item = instr[i];
if (!string.IsNullOrWhiteSpace(item))
{
output1[i] = new String(item.TrimStart().Substring(0, 1).ToUpper().ToCharArray());
}
}