Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Manipulating a string array using a Lambda Expression

5.00/5 (1 vote)
7 Nov 2012CPOL1 min read 27K  
This is an alternative for Manipulating a string array using a Lambda Expression

Introduction

This is an alternative to tip Manipulating a string array using a Lambda Expression.

The idea is to take the first character of each string and return the results as an array. 

Using the code

For the test, I expanded the string array to contain also an empty string and a null value to verify that the code runs as expected also in these situations.

To extract the first letters, a query like the following can be written:

C#
string[] inputarray = new string[] { "Bharti", "Mangesh", "", null, "Akash", "Bhavya", "Chetan" };
char[] outputarray = (from item in inputarray
                      where item != null
                      select item.FirstOrDefault<char>()).ToArray(); 

So the above code loops through all the elements in the input array. In order to prevent null exceptions, elements containing a null value are skipped using the where clause.

For each non-null element the first character is extracted using FirstOrDefault method. Because the input array may contain empty strings, it's important to also include the default value in the select clause. 

So the result is:  

Element index Char value Char 
66 'B' 
77 'M' 
'\0' 
65 'A' 
66 'B' 
67 'C' 
 

The same query can also be written like the  the following (the actual code line is split for readability): 

C#
char[] outputarray = inputarray.Where(item => item != null)
                               .Select(item => item.FirstOrDefault<char>())
                               .ToArray();  

These are just few examples how the character can be extracted. 

One additional example could be, if the third character should always be returned, the statement could look like this (again, the actual code line is split for readability): 

C#
char[] outputarray = inputarray.Where(item => item != null)
                               .Select(item => item.Skip<char>(2).FirstOrDefault<char>())
                               .ToArray(); 

So before taking the first (or the default) character, two characters are skipped with the Skip method. With the test data, the result would be:  

Element index Char value Char 
97 'a' 
1  110 'n' 
'\0' 
97 'a' 
97 'a' 
101 'e' 

References

References for the methods used:

History  

  • November 7, 2012: Alternative created. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)