C#新手技术问询:字符串列表转数组、整数数组并求和方法
解决你的C#字符串列表转整数数组并求和的问题
Hey there! As someone starting out with C#, this is a great first problem to tackle—let's walk through exactly how to make this work for your TextBox and Button setup.
核心步骤拆解
First, let's map your technical question to your actual scenario:
- Step 1: Collect all TextBox values into a list (or directly into a collection)
- Step 2: Convert that list to a string array (super straightforward in C#)
- Step 3: Safely convert the string array to an integer array (handle bad user input!)
- Step 4: Calculate the sum of the integer array
完整实现代码
Here's a ready-to-use button1_Click event handler that fits your scenario. I've added comments to explain every part so you can follow along:
private void button1_Click(object sender, EventArgs e) { // Step 1: Gather all TextBox controls and their values // We'll create a list of TextBoxes first to make iteration easy List<TextBox> numberTextBoxes = new List<TextBox> { d1, d2, d3, d4 }; List<string> stringValues = new List<string>(); foreach (TextBox tb in numberTextBoxes) { // Add each TextBox's text to our string list (trim whitespace just in case) stringValues.Add(tb.Text.Trim()); } // Step 2: Convert string list to string array (List has a built-in ToArray() method) string[] stringArray = stringValues.ToArray(); // Step 3: Convert string array to integer array (with error handling!) List<int> integerList = new List<int>(); foreach (string value in stringArray) { // Use int.TryParse to safely check if the input is a valid integer if (int.TryParse(value, out int number)) { integerList.Add(number); } else { // Optional: Alert the user if they entered something non-numeric MessageBox.Show($"Warning: '{value}' is not a valid number and will be skipped."); } } int[] integerArray = integerList.ToArray(); // Step 4: Calculate the sum of the integer array // Option 1: Use LINQ (clean and concise—add using System.Linq; at the top of your file!) int totalSum = integerArray.Sum(); // Option 2: Use a loop (great for learning how summation works under the hood) // int totalSum = 0; // foreach (int num in integerArray) // { // totalSum += num; // } // Show the result to the user MessageBox.Show($"Total Sum: {totalSum}"); }
关键注意事项
- Input Validation: Using
int.TryParseinstead ofint.Parseis crucial here—if a user enters letters or symbols, your program won't crash, and you can give them a friendly warning. - LINQ Requirement: If you use the
Sum()method, make sure to addusing System.Linq;at the very top of your C# file (above your class declaration). - Scalability: If you add more TextBoxes later (like d5, d6), just add them to the
numberTextBoxeslist—no need to rewrite the rest of the code!
内容的提问来源于stack exchange,提问作者Walid
相关产品推荐
相关产品推荐

