c# Leaner way of initializing int array

前端 未结 4 1519
南方客
南方客 2021-01-20 14:50

Having the following code is there a leaner way of initializing the array from 1 to the number especified by a variable?

int nums=5;
int[] array= new int[num         


        
相关标签:
4条回答
  • 2021-01-20 15:26
    int[] array = Enumerable.Range(0, nums).ToArray();
    
    0 讨论(0)
  • 2021-01-20 15:37

    Maybe I'm missing something here, but here is the best way I know of:

    int[] data = new int [] { 383, 484, 392, 975, 321 };

    from MSDN

    even simpler:

    int[] data = { 383, 484, 392, 975, 321 };

    0 讨论(0)
  • 2021-01-20 15:44

    Using Enumerable.Range

    int[] array = Enumerable.Range(0, nums).ToArray();
    
    0 讨论(0)
  • 2021-01-20 15:51

    Use Enumerable.Range() method instead of. Don't forget to add System.Linq namespace. But this could spend little bit high memory. You can use like;

    int[] array = Enumerable.Range(0, nums).ToArray();
    

    Generates a sequence of integral numbers within a specified range.

    0 讨论(0)
提交回复
热议问题