C# 数组初始化 - 使用非默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/136836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 15:05:16  来源:igfitidea点击:

C# Array initialization - with non-default value

提问by Rob

What is the slickest way to initialize an array of dynamic size in C# that you know of?

你知道的在 C# 中初始化动态大小数组的最巧妙方法是什么?

This is the best I could come up with

这是我能想到的最好的

private bool[] GetPageNumbersToLink(IPagedResult result)
{
   if (result.TotalPages <= 9)
      return new bool[result.TotalPages + 1].Select(b => true).ToArray();

   ...

采纳答案by Mark Cidade

use Enumerable.Repeat

使用Enumerable.Repeat

Enumerable.Repeat(true, result.TotalPages + 1).ToArray()

回答by Matt Hamilton

Untested, but could you just do this?

未经测试,但你能这样做吗?

return result.Select(p => true).ToArray();

Skipping the "new bool[]" part?

跳过“new bool[]”部分?

回答by Matt Hamilton

I would actually suggest this:

我实际上建议这样做:

return Enumerable.Range(0, count).Select(x => true).ToArray();

This way you only allocate one array. This is essentially a more concise way to express:

这样你只分配一个数组。这本质上是一种更简洁的表达方式:

var array = new bool[count];

for(var i = 0; i < count; i++) {
   array[i] = true;
}

return array;

回答by Neil Hewitt

EDIT: as a commenter pointed out, my original implementation didn't work. This version works but is rather un-slick being based around a for loop.

编辑:正如评论者指出的那样,我的原始实现不起作用。此版本有效,但基于 for 循环相当不流畅。

If you're willing to create an extension method, you could try this

如果你愿意创建一个扩展方法,你可以试试这个

public static T[] SetAllValues<T>(this T[] array, T value) where T : struct
{
    for (int i = 0; i < array.Length; i++)
        array[i] = value;

    return array;
}

and then invoke it like this

然后像这样调用它

bool[] tenTrueBoolsInAnArray = new bool[10].SetAllValues(true);

As an alternative, if you're happy with having a class hanging around, you could try something like this

作为替代方案,如果你对有一个班级闲逛感到满意,你可以尝试这样的事情

public static class ArrayOf<T>
{
    public static T[] Create(int size, T initialValue)
    {
        T[] array = (T[])Array.CreateInstance(typeof(T), size);
        for (int i = 0; i < array.Length; i++)
            array[i] = initialValue;
        return array;
    }
}

which you can invoke like

你可以像这样调用

bool[] tenTrueBoolsInAnArray = ArrayOf<bool>.Create(10, true);

Not sure which I prefer, although I do lurv extension methods lots and lots in general.

不确定我更喜欢哪个,尽管我通常做了很多 lurv 扩展方法。

回答by Nigel Touch

If by 'slickest' you mean fastest, I'm afraid that Enumerable.Repeatmay be 20x slower than a forloop. See http://dotnetperls.com/initialize-array:

如果“最流畅”是指最快,恐怕Enumerable.Repeat可能比for循环慢 20 倍。请参阅http://dotnetperls.com/initialize-array

Initialize with for loop:             85 ms  [much faster]
Initialize with Enumerable.Repeat:  1645 ms 

So use Dotnetguy's SetAllValues() method.

所以使用 Dotnetguy 的 SetAllValues() 方法。

回答by Ohad Schneider

Many times you'd want to initialize different cells with different values:

很多时候你想用不同的值初始化不同的单元格:

public static void Init<T>(this T[] arr, Func<int, T> factory)
{
    for (int i = 0; i < arr.Length; i++)
    {
        arr[i] = factory(i);
    }
}

Or in the factory flavor:

或在工厂风味:

public static T[] GenerateInitializedArray<T>(int size, Func<int, T> factory)
{
    var arr = new T[size];
    for (int i = 0; i < arr.Length; i++)
    {
        arr[i] = factory(i);
    }
    return arr;
}