This is my version of the knapsack challenge and I was wondering if there was a way to do it so it doesn't go through the `foreach` statement so many times. At the minute it goes through it thousands of times to get he closes value to the target number, which takes long time to do, I was wondering if there was a way to either do it without `foreach` or make it quick with the `foreach`.

```
private void btnGenerate_Click(object sender, RoutedEventArgs e)
{
    string input;
    string bag;
    int goal;
    int count = 0;

    int element;
    List<int> finalResult = new List<int>();
    do
    {
        bag = txtBag.Text;
    }
    while (!int.TryParse(bag, out goal));
    input = txtGenerate.Text;
    string[] elementsText = input.Split(' ');
    List<int> elementsList = new List<int>();
    foreach (string elementText in elementsText)
    {

        if (int.TryParse(elementText, out element))
        {
            elementsList.Add(element);
        }
    }
    Solver solver = new Solver();
    List<List<int>> results = solver.Solve(goal, elementsList.ToArray());
    int closestValue = 0;
    foreach (List<int> result in results)
    {
        count++;
        int totalValue = result.Sum(x => Convert.ToInt32(x));

        if (totalValue >= closestValue)
        {
            closestValue = totalValue;
            finalResult = result;
            txtSum.Text = closestValue.ToString();

        }
    }

    foreach (int value in finalResult)
    {
        txtCount.Text = count.ToString();

        cboResult.ItemsSource = finalResult;

    }
}

```

I also have a class with this in:

```
public class Solver
{
    public List<List<int>> mResults;
    public int closestValue = 0;
    public List<List<int>> Solve(int goal, int[] elements)
    {
        mResults = new List<List<int>>();
        RecursiveSolve(goal, 0, new List<int>(), new List<int>(elements), 0);
        return mResults;
    }

    private void RecursiveSolve(int goal, int currentSum,
    List<int> included, List<int> notIncluded, int startIndex)
    {
        for (int index = startIndex; index < notIncluded.Count; index++)
        {
            int nextValue = notIncluded[index];
            if (currentSum + nextValue <= goal && currentSum + nextValue >= closestValue)
            {
                List<int> newResult = new List<int>(included);
                newResult.Add(nextValue);
                mResults.Add(newResult);
                closestValue = currentSum + nextValue;
            }
            if (currentSum + nextValue < goal)
            {

                List<int> nextIncluded = new List<int>(included);
                nextIncluded.Add(nextValue);
                List<int> nextNotIncluded = new List<int>(notIncluded);
                nextNotIncluded.Remove(nextValue);
                RecursiveSolve(goal, currentSum + nextValue,
                    nextIncluded, nextNotIncluded, startIndex++);
            }
        }
    }
}

```