首页 > 解决方案 > 如何删除 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# 的目标值?

标签: c#listlinqfor-loop

解决方案


如果我的理解是正确的:

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]


推荐阅读