简体   繁体   中英

C# Array initialization - with non-default value

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

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();

   ...

If by 'slickest' you mean fastest, I'm afraid that Enumerable.Repeat may be 20x slower than a for loop. See 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.

使用Enumerable.Repeat

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

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.

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.

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;

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;
}

Untested, but could you just do this?

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

Skipping the "new bool[]" part?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM