0

i am getting string array on runtime like this

    string[] array1 = {"5", "4", "2"};

values in array is added on runtime on the basis of checkbox selection from

screen (Note: i have 7 check boxes on screen )

if i check 3 check boxes then 3 values will be add in array1 but i want to add

zero at the end of the array in remaining 4 positions in array like this :

 string[] array1 = {"5", "4", "2","0" ,"0","0" , "0"};

during runtime just to fix all 7 position in array ...what should i do ??

4
  • 1
    Your question is confusing. You recieve an array with 3 values. Then if three checkboxes are checked you add 3 values? What three values? You have the exact same values you started with and you are simple adding zeros... Commented Apr 30, 2020 at 8:57
  • values will be added on the basis of some calculation i just want to add zero on the un checked check boxes position Commented Apr 30, 2020 at 8:59
  • Is position meaningul? If checkbox2 is unchecked, then 0 should be added at index 2 or you simply want to append 0s to the end of the array until the total amout is 7? Commented Apr 30, 2020 at 9:02
  • just append at the end of the array Commented Apr 30, 2020 at 9:05

2 Answers 2

1

I don't get the usage of your requirement. But you can fill up the array with "0" with the following code:

List<string> list = array1.ToList();
for (int i = array1.Length; i < 7; i++)
{
    list.Add("0");
}
array1 = list.ToArray();
Sign up to request clarification or add additional context in comments.

Comments

0

You can do the following:

const int paddedSize = 7;
var newArray = array1.Concat(Enumerable.Repeat("0", paddedSize - array1.Length)).ToArray();

But maybe you'll understand it better without using Linq; the type you want to use is List<string> which can be dynamically resized, arrays can't. In order to get a list out of an array, you can use the linq extension:

var resized = array1.ToList();

Or

var resized = new List<string>(array1);

And now you simply add 0s until the total count of items is 7:

while (resized.Count < paddedSize)
    resized.Add("0");

And back to an array:

var newArray = resized.ToArray();

1 Comment

added zero with the help of list ...thanks for your time

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.