键值对列表

我有一个包含以下元素的列表:

{[A,1] ; [B,0] ; [C,0] ; [D,2]; [E,0] ; [F,8]} 

当Variable = 3 – >我希望返回值为A,D

当变量= 11 – >返回值为A,D,F时

当2 – >返回值为D时

等等。

  int sum = myList.Sum(x => x.Value) 

如何获得相应的密钥(A,D,F)?

在这个问题中使用其中一个子集方法

 var list = new List>() { new KeyValuePair("A", 1), new KeyValuePair("B", 0), new KeyValuePair("C", 0), new KeyValuePair("D", 2), new KeyValuePair("E", 8), }; int input = 11; var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input); 

编辑

一个完整的控制台应用

 using System; using System.Collections.Generic; using System.Linq; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { var list = new List>() { new KeyValuePair("A", 1), new KeyValuePair("B", 2), new KeyValuePair("C", 3), new KeyValuePair("D", 4), new KeyValuePair("E", 5), new KeyValuePair("F", 6), }; int input = 12; var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input); foreach (var res in alternatives) { Console.WriteLine(String.Join(",", res.Select(x => x.Key))); } Console.WriteLine("END"); Console.ReadLine(); } } public static class Extenions { public static IEnumerable> SubSets(this IEnumerable enumerable) { List list = enumerable.ToList(); ulong upper = (ulong)1 << list.Count; for (ulong i = 0; i < upper; i++) { List l = new List(list.Count); for (int j = 0; j < sizeof(ulong) * 8; j++) { if (((ulong)1 << j) >= upper) break; if (((i >> j) & 1) == 1) { l.Add(list[j]); } } yield return l; } } } }