假设我有一个列表:
List<int> _arr = new List<int> {1, 3, 4};
Run Code Online (Sandbox Code Playgroud)
而且是一个目标 4
我想回到{1, 3}作为1 + 3 = 4和{4}作为4 = 4使用LINQ从给定的列表.
我怎么做?
Geo*_*ett 10
这很容易,一旦我们有一个方法来获得一个枚举/列表的所有子集
(这里找到答案:最优雅的方式来获得在C#中的数组的所有子集)
using System;
using System.Collections.Generic;
using System.Linq;
public static class Program
{
static void Main(string[] args)
{
var test = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var target = 6;
var matches = from subset in test.SubSetsOf()
where subset.Sum() == target
select subset;
Console.WriteLine("Numbers: {0}", test.Select(i => i.ToString()).Aggregate((a, n) => a + ", " + n));
Console.WriteLine("Target: {0}", target);
foreach (var match in matches)
{
Console.WriteLine(match.Select(m => m.ToString()).Aggregate((a, n) => a + " + " + n) + " = " + target.ToString());
}
Console.ReadKey();
}
public static IEnumerable<IEnumerable<T>> SubSetsOf<T>(this IEnumerable<T> source)
{
// Deal with the case of an empty source (simply return an enumerable containing a single, empty enumerable)
if (!source.Any())
return Enumerable.Repeat(Enumerable.Empty<T>(), 1);
// Grab the first element off of the list
var element = source.Take(1);
// Recurse, to get all subsets of the source, ignoring the first item
var haveNots = SubSetsOf(source.Skip(1));
// Get all those subsets and add the element we removed to them
var haves = haveNots.Select(set => element.Concat(set));
// Finally combine the subsets that didn't include the first item, with those that did.
return haves.Concat(haveNots);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9
Target: 6
1 + 2 + 3 = 6
1 + 5 = 6
2 + 4 = 6
6 = 6
Run Code Online (Sandbox Code Playgroud)