2011-07-26 12 views

Respuesta

9

No sé de nada en el marco que hace eso, pero es bastante fácil de implementar:

// Note: start is inclusive, end is exclusive (as is conventional 
// in computer science) 
public static void Fill<T>(T[] array, int start, int end, T value) 
{ 
    if (array == null) 
    { 
     throw new ArgumentNullException("array"); 
    } 
    if (start < 0 || start >= end) 
    { 
     throw new ArgumentOutOfRangeException("fromIndex"); 
    } 
    if (end >= array.Length) 
    { 
     throw new ArgumentOutOfRangeException("toIndex"); 
    } 
    for (int i = start; i < end; i++) 
    { 
     array[i] = value; 
    } 
} 

O si desea especificar el recuento en lugar del inicio/finalización:

public static void Fill<T>(T[] array, int start, int count, T value) 
{ 
    if (array == null) 
    { 
     throw new ArgumentNullException("array"); 
    } 
    if (count < 0) 
    { 
     throw new ArgumentOutOfRangeException("count"); 
    } 
    if (start + count >= array.Length) 
    { 
     throw new ArgumentOutOfRangeException("count"); 
    } 
    for (var i = start; i < start + count; i++) 
    { 
     array[i] = value; 
    } 
} 
+0

Espero que mi edición esté justificada ... o nombre la variable como 'uptoIndex' – nawfal

+0

@nawfal: No, fue deliberadamente (aunque no consistentemente) exclusivo. Lo he arreglado y he agregado una alternativa. –

+0

Jon, ¿por qué compruebas casos excepcionales y te arrojas cuando el clr hace eso? Estoy un poco desconcertado por este tipo de diseño. ¿No bastaría solo con la segunda verificación condicional (en ambos ejemplos)? – nawfal

1

Trate como esto

Array.Copy(source, target, 5); 

Para obtener más información here

+4

que no hace lo mismo que 'fill'. –

+0

pero no es una matriz de destino para copiar ... está tomando longitud ... mynewArray is int [] – usr021986

+0

La sugerencia de Rasel es correcta. Ejemplo de trabajo: int [] arr = new int [1000]; Array.Copy (arr.Select (i => 5) .ToArray(), arr, arr.Length); – dmitry

0

Parece que le gustaría hacer algo de la misma familia

int[] bar = new int[] { 1, 2, 3, 4, 5 }; 
int newSize = 10; 
int[] foo = Enumerable.Range(0, newSize).Select(i => i < bar.Length ? bar[i] : -1).ToArray(); 

Creación de una nueva matriz más grande con los viejos valores y llenando el extra.

Para un relleno sencillo tratar

int[] foo = Enumerable.Range(0, 10).Select(i => -1).ToArray(); 

o un rango sub

int[] foo = new int[10]; 
Enumerable.Range(5, 9).Select(i => foo[i] = -1); 
Cuestiones relacionadas