C#实现列表/数组元素相加所有可能组合技术求助
Hey there! Let's figure out how to adjust your code to work with an int[] array instead of a List<int>, plus fix a small issue in your original List-based code to make it more robust.
First, let's spot the small problem in your original code
Your current code uses a hardcoded 4 for the loop limits, which works only if your initial List has exactly 4 elements. If you ever change the initial array, this will break. A better approach is to capture the initial count of the List first, then loop against that:
int initialListCount = List.Count; for (int noSelected = 0; noSelected < initialListCount; noSelected++) { for(int noAdded = 0; noAdded < initialListCount; noAdded++) { List.Add(List[noSelected] + List[noAdded]); } }
This way, it'll work no matter how many elements you start with.
Now, let's implement this for an int[] array
The core idea is the same: iterate over all pairs of elements, calculate their sum, collect those sums, then remove duplicates. Using a HashSet<int> is more efficient here because it automatically handles duplicates as we add elements, instead of collecting everything first and then calling Distinct().
Here's the full code:
namespace CombinationWork { class Program { static void Main(string[] args) { // Your input int array int[] a = new int[] { 1, 2, 5, 10 }; // HashSet automatically handles duplicate sums HashSet<int> uniqueSums = new HashSet<int>(); // Iterate over all pairs (including element + itself) for (int i = 0; i < a.Length; i++) { for (int j = 0; j < a.Length; j++) { uniqueSums.Add(a[i] + a[j]); } } // Output each unique sum foreach (int sum in uniqueSums) { Console.WriteLine(sum); } Console.ReadLine(); } } }
Why use HashSet instead of List?
- Efficiency:
HashSetchecks for duplicates when adding each element, so you avoid the extra step of filtering duplicates later withDistinct(). - Cleaner code: It's more intuitive to use a collection that's designed for unique values when that's exactly what you need.
If you prefer to stick with a List (maybe for specific ordering needs), you can do this instead:
List<int> allSums = new List<int>(); for (int i = 0; i < a.Length; i++) { for (int j = 0; j < a.Length; j++) { allSums.Add(a[i] + a[j]); } } // Remove duplicates and convert back to List List<int> uniqueSums = allSums.Distinct().ToList();
Just note this is slightly less efficient since it first collects all sums (including duplicates) before filtering.
内容的提问来源于stack exchange,提问作者Khwaja Hussam Quasmi

