我有一个数字数组和一个变量S.我想在C#中使用LINQ从中选择前k个元素,这样k个元素的总和小于S.
例如:
int []数字= {1,4,53,23,15,12,15,25,45,13,16,76,43,82,24}; int S = 100;
结果将是一个数组:{1,4,53,23,15}
答案 0 :(得分:6)
看看TakeWhile:
int[] Numbers = { 1, 4, 53, 23, 15, 12, 15, 25, 45, 13, 16, 76, 43, 82, 24 };
int total = 0;
var result = Numbers.TakeWhile(i =>
{
total += i;
return total < s
});