Pages

Monday, September 29, 2014

Interesting C# functions and their usage

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], outarrIntUserID[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 = { truefalsetruetruefalsetrue};

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, usingarrAnswerChoices.Count(choice => (!choice)); will give the number of false values present in the array.
 
Hope this helps you