c# - 如何删除 List 中的每个 N 项,直到 List.Count 超过目标值?
问题描述
有一个简短的列表。它的值无关紧要:
List<short> resultTemp = new List<short>{1,2,3,4,5,6,7,8,9...};
此代码应通过从中删除每个第 N 项来减少结果列表计数。
示例 1:
List<short>{1,2,3,4,5,6,7,8,9,10}.Count == 10;
var targetItemsCount = 5;
结果应该是 {1,3,5,7,9} 并且 result.Count 应该是 == 5
示例 2:
List<short>{1,2,3,4,5,6,7,8,9}.Count == 9;
var targetItemsCo:nt = 3;
结果应该是 {1,4,7} 并且 result.Count 应该是 == 3
但它应该停止删除它,在某处使结果计数等于 targetItemsCount(此代码中为 42,但它的值无关紧要)。代码是:
var currentItemsCount = resultTemp.Count;
var result = new List<short>();
var targetItemsCount = 42;
var counter = 0;
var counterResettable = 0;
if (targetItemsCount < currentItemsCount)
{
var reduceIndex = (double)currentItemsCount / targetItemsCount;
foreach (var item in resultTemp)
{
if (counterResettable < reduceIndex ||
result.Count + 1 == currentItemsCount - counter)
{
result.Add(item);
counterResettable++;
}
else
{
counterResettable = 0;
}
counter++;
}
}
而本例中的 resault.Count 等于 41,但应该是 == targetItemsCount == 42;
如何删除 List 中的每个 N 项,直到 List.Count 多于 C# 的目标值?
解决方案
如果我的理解是正确的:
public static void run()
{
var inputs =
new List<Input>{
new Input{
Value = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },`
TargetCount = 5, ExpectedOutput= new List<int>{1,3,5,7,9}
},
new Input{
Value = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 },
TargetCount = 3, ExpectedOutput= new List<int>{1,4,7}
},
};
foreach (var testInput in inputs)
{
Console.WriteLine($"# Input = [{string.Join(", ", testInput.Value)}]");
var result = Reduce(testInput.Value, testInput.TargetCount);
Console.WriteLine($"# Computed Result = [{string.Join(", ", result)} ]\n");
}
}
static List<int> Reduce(List<int> input, int targetItemsCount)
{
while (input.Count() > targetItemsCount)
{
var nIndex = input.Count() / targetItemsCount;
input = input.Where((x, i) => i % nIndex == 0).ToList();
}
return input;
}
class Input
{
public List<int> ExpectedOutput;
public List<int> Value;
public int TargetCount;
}
结果 :
输入 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
计算结果 = [1, 3, 5, 7, 9 ]输入 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
计算结果 = [1, 4, 7]
推荐阅读
- c# - 可空的 int 文化特定于 toString()
- asp.net - Identity Server 不调用 BackChannelLogout url
- django - 更新表单时如何在下拉列表中显示已选择的选项
- javascript - 返回值没有在另一个返回有效载荷中被拾取
- google-apps-script - 无法在我的域外发送电子邮件,电子邮件被退回
- sitecore - Sitecore 本地实例设置中的渲染错误
- keras - 为什么我使用发电机时精度不好?
- scroll - 0 级键值未存储在 1 级记录中
- angular - anugular 6同时从多个组件订阅主题不起作用
- html - 使用 CSS 获取 flexbox 中的行数/行数