I have faced some situations earlier in which something was getting done by looping though data structures but i wanted to overcome that. Then in process of avoiding those looping, i came to know some interesting and helpful functions in C#. These are:
Select() function:
How to convert a string array to an integer array?
I was having a string array as
string[] arrUserIDs = { “315”, “610”, “1”, “13”, “456” };
I wanted to convert it to an array of integers. The previous and simple approach was to loop through each string and convert into interger, like:
int[] arrIntUserID = new int[arrUserIDs.Length]; int userIDCounter = 0; foreach(string userID in arrUserIDs) { int.TryParse(arrUserIDs[userIDCounter], out arrIntUserID[userIDCounter]); userIDCounter++; }
But why write all these things if you can use Select() for doing the above task. The above code can be written as:
int[] arrIntUserID = arrUserIDs.Select(id => int.Parse(id)).ToArray();
Where() function: How to remove empty strings from an array?
I was having a string array like
string[] arrNames = { "315", "610", "1", "13", "456" };
First I was following the same loop approach for removing empty string from a string array. But then I used Where() function and by using it my code change to
arrNames = arrNames.Where(name => !string.IsNullOrEmpty(name)).ToArray();
Count() function: How to count number of true values in an array?
I was having a boolean array like
bool[] arrAnswerChoices = { true, false, true, true, false, true };
I wanted to know how many true values are present in the array. Then I came to know the powerfulness of count() function and used it as follows:
arrAnswerChoices.Count(choice => (choice));
The above code gave me the number of true values present in the boolean array, using
arrAnswerChoices.Count(choice => (!choice));
will give the number of false values present in the array.
Hope this helps you