This is called the problem of the sum of the subset and is considered a complex problem in computer science. Not difficult, how difficult, but difficult to do quickly - you can easily write an algorithm to do this, but for significant inputs it will easily take billions of years.
If you are happy with the slow solution, which is practically possible for small inputs, try something like this:
Generate all subsets of the input list.
For each subset, we compute the sum of the elements in this subset.
Returns the first subset for which the sum matches.
Here is a method that returns all subsets (in fact, subsequences, since it maintains the order of the elements, although this does not matter in your case):
So now you can write something like this ...
var result = list.Subsequences() .FirstOrDefault(ss => ss.Sum(item => item.Value) == sum);
Timwi source share