I have a list with below elements:
{[A,1] ; [B,0] ; [C,0] ; [D,2]; [E,0] ; [F,8]}
When Variable =3 -> i want the return value to be A,D
When variable =11 -> return value to be A, D, F
when 2 -> return value to be D
and so on.
int sum = myList.Sum(x => x.Value)
how to get the corresponding Key (A,D,F)?
A value in the key-value pair can be a number, a string, a list, a tuple, or even another dictionary. In fact, you can use a value of any valid type in Python as the value in the key-value pair. A key in the key-value pair must be immutable.
A key-value pair consists of two related data elements: A key, which is a constant that defines the data set (e.g., gender, color, price), and a value, which is a variable that belongs to the set (e.g., male/female, green, 100). Fully formed, a key-value pair could look like these: gender = male. color = green.
The KeyValuePair class stores a pair of values in a single list with C#. Set KeyValuePair and add elements − var myList = new List<KeyValuePair<string, int>>(); // adding elements myList. Add(new KeyValuePair<string, int>("Laptop", 20)); myList.
Using one of the subsets method in this question
var list = new List<KeyValuePair<string, int>>() { new KeyValuePair<string, int>("A", 1), new KeyValuePair<string, int>("B", 0), new KeyValuePair<string, int>("C", 0), new KeyValuePair<string, int>("D", 2), new KeyValuePair<string, int>("E", 8), }; int input = 11; var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);
EDIT
a full console application:
using System; using System.Collections.Generic; using System.Linq; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { var list = new List<KeyValuePair<string, int>>() { new KeyValuePair<string, int>("A", 1), new KeyValuePair<string, int>("B", 2), new KeyValuePair<string, int>("C", 3), new KeyValuePair<string, int>("D", 4), new KeyValuePair<string, int>("E", 5), new KeyValuePair<string, int>("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<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable) { List<T> list = enumerable.ToList(); ulong upper = (ulong)1 << list.Count; for (ulong i = 0; i < upper; i++) { List<T> l = new List<T>(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; } } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With