Replace empty string with 0 in array

I have a grid. When I enter some numeric values in that grid, it is saved in array.

                RegArrayLoopEL = RegArrayEL[a].Split('ô');

Now In case an array has empty string “” I have to replace it with 0
One way that I can do is

                if (RegArrayLoopEL[1] == "")
                {
                    RegArrayLoopEL[1] = "0";
                }

But for that I will have to use a lot of if conditions for every array. Is there any alternative for it? or any other way this can be done?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can do it on assignment:

RegArrayLoopEL = RegArrayEL[a].Split('ô').Select(str => str == "" ? "0" : str).ToArray();

You could create a function or delegate to clean it up a bit and make it so if you change the logic you just need to change it one place:

string[] ReplaceEmptyStrings(IEnumerable<string> strings) =>
    strings.Select(str => str == "" ? "0" : str).ToArray();

And then your assignments would be:

RegArrayLoopEL = ReplaceEmptryStrings(RegArrayEL[a].Split('ô'));


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x