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:
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 |
0 | 66 | 'B' |
1 | 77 | 'M' |
2 | 0 | '\0' |
3 | 65 | 'A' |
4 | 66 | 'B' |
5 | 67 | 'C' |
The same query can also be written like the the following (the actual code line is split for readability):
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):
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 |
0 | 97 | 'a' |
1 | 110 | 'n' |
2 | 0 | '\0' |
3 | 97 | 'a' |
4 | 97 | 'a' |
5 | 101 | 'e' |
References
References for the methods used:
History
- November 7, 2012: Alternative created.