使用Linq每x次递增一次浮点数组递增索引值

时间:2014-07-30 20:05:16

标签: c# arrays linq

初始化大小为n的float数组的最有效方法是使用linq

每x个索引递增一次

例如,如果数组增量为5,从10开始,增量大小为5,则数组看起来像

float[] x = {10, 10, 10, 10, 10, 15, 15, 15, 15, 15, 20, 20, 20, 20, 20, 25, 25, 25, 25, 25}

3 个答案:

答案 0 :(得分:7)

你可以争论什么是“最好”的方式。咬我怎么做的方式。首先,我将创建一个帮助您生成Enumerables的帮助方法。

public static IEnumerable<T> Unfold<T>(T seed, Func<T, T> accumulator) {
    var nextValue = seed;
    while ( true ) {
        yield return nextValue;
        nextValue = accumulator(nextValue);
    }
}

这是一般助手功能。例如

Unfold(1, x => x*2)

它会为您创建一个新的IEnumerable,其中每个新数字都是前一个数字的两倍。您应该使用.Take()或.TakeWhile()方法来限制生成的数量。例如,如果您只想要功率为2的前10个数字

Unfold(1, x => x*2).Take(10).ToList()

您获得了一个包含[1,2,4,8,16,32,64,128,256,512]

的列表

Unfold()之类的东西通常有助于创建任意的Enumerables。

现在创建你的列表。你想创建一个总是加5的列表,然后每个数字重复5次,你想要重复4次。所以你的第一步是

Unfold(10, x => x+5).Take(4)

它将创建一个包含[10, 15, 20, 25]的IEnumerable。现在下一步是每次重复5次。

您可以使用Enumerable.Repeat()执行此操作。逻辑是。

  1. 浏览您的清单
  2. 使用Enuerable.Repeat
  3. 从每个数字创建一个新的Enumerable
  4. 将每个Enumerable整理为一个Enumerable
  5. 上面的逻辑正是SelectMany()所做的。所以解决方案是

    var nums = Unfold(10, x => x+5).Take(4).SelectMany(x => Enumerable.Repeat(x, 5));
    

    现在nums是以下列表[10, 10, 10, 10, 10, 15, 15, 15, 15, 15, 20, 20, 20, 20, 20, 25, 25, 25, 25, 25]

答案 1 :(得分:1)

这个怎么样:

var n = 20;
var start = 10;
var step = 5;
var increment = 5;
var x = Enumerable
    .Range(0, n)
    .Select(y => (float)start + increment * (y / step))
    .ToArray();

请注意,虽然我非常喜欢Linq,但我必须同意Robert Harvey在这种情况下循环可能更清晰。

答案 2 :(得分:0)

Linq可能不是你解决这个问题的最佳选择。这就是说,也许是这样的事情?

var groupCount = 4;
var elementsPerGroup = 5;
var increment = 5;

var a = Enumerable
    .Range(0, groupCount)
    .Select(i => Enumerable
                     .Range(0, elementsPerGroup)
                     .Select(r => (float)(10 + increment * i)).ToArray())
    .SelectMany(i => i)
    .ToArray();