计算器历史记录存储:如何简化未知数量条目的List.Add动态实现
Looks like you're stuck with repetitive code for logging calculator history based on input number counts—totally get how tedious that duplication can be! Let’s break down a clean, scalable way to simplify this so you don’t need a separate if block for every possible number of inputs.
First, here’s the redundant code you’re working with:
if (amountNumbers == 2) { memory.Add(userNumbers[0].ToString() + " " + op + " " + userNumbers[1].ToString() + " = " + calculation.ToString()); userNumbers.Clear(); } if (amountNumbers == 3) { memory.Add(userNumbers[0].ToString() + " " + op + " " + userNumbers[1].ToString() + " " + op + " " + userNumbers[2].ToString() + " = " + calculation.ToString()); userNumbers.Clear(); } if (amountNumbers == 4) { memory.Add(userNumbers[0].ToString() + " " + op + " " + userNumbers[1].ToString() + " " + op + " " + userNumbers[2].ToString() + " " + op + " " + userNumbers[3].ToString() + " = " + calculation.ToString()); userNumbers.Clear(); } if (amountNumbers == 5) { memory.Add(userNumbers[0].ToString() + " " + op + " " + userNumbers[1].ToString() + " " + op + " " + userNumbers[2].ToString() + " " + op + " " + userNumbers[3].ToString() + " " + op + " " + userNumbers[4].ToString() + " = " + calculation.ToString()); userNumbers.Clear(); }
The Simplified Solution
The core trick here is using string.Join to dynamically build your calculation expression, regardless of how many numbers the user entered (as long as it’s within your supported range). This eliminates all duplicate if logic and makes the code easy to extend later if you want to support more than 5 numbers.
Here’s the refactored code:
// Validate we have a valid number count and matching elements in userNumbers if (amountNumbers is >= 2 and <= 5 && userNumbers.Count == amountNumbers) { // Convert numbers to strings and join them with " [op] " separators string expression = string.Join($" {op} ", userNumbers.Select(num => num.ToString())); // Combine expression with result and add to history memory.Add($"{expression} = {calculation.ToString()}"); userNumbers.Clear(); }
How It Works
- Validation Check: First we confirm
amountNumbersfalls within your original 2-5 range, and thatuserNumbersactually contains that many elements—this prevents errors from mismatched counts. - Dynamic Expression Building:
string.Jointakes your formatted separator (" {op} ") and inserts it between every converted number string. For example, 3 numbers will automatically become"num1 op num2 op num3"without you writing each segment manually. - Final History Entry: We just append the calculation result to the built expression, add it to your
memorylist, and clear the input numbers like before.
This approach keeps your code clean, maintainable, and flexible—no more copying and pasting if blocks for each new number count!
内容的提问来源于stack exchange,提问作者Christopher Reineborn

