Adding elements to a C# array

前端 未结 10 409
野趣味
野趣味 2021-01-11 19:29

I would like to programmatically add or remove some elements to a string array in C#, but still keeping the items I had before, a bit like the VB function ReDim Preserve.

相关标签:
10条回答
  • 2021-01-11 19:59

    If you really won't (or can't) use a generic collection instead of your array, Array.Resize is c#'s version of redim preserve:

    var  oldA = new [] {1,2,3,4};
    Array.Resize(ref oldA,10);
    foreach(var i in oldA) Console.WriteLine(i); //1 2 3 4 0 0 0 0 0 0
    
    0 讨论(0)
  • 2021-01-11 20:01

    Since arrays implement IEnumerable<T> you can use Concat:

    string[] strArr = { "foo", "bar" };
    strArr = strArr.Concat(new string[] { "something", "new" });
    

    Or what would be more appropriate would be to use a collection type that supports inline manipulation.

    0 讨论(0)
  • 2021-01-11 20:05

    You should take a look at the List object. Lists tend to be better at changing dynamically like you want. Arrays not so much...

    0 讨论(0)
  • 2021-01-11 20:05

    You can use this snippet:

    static void Main(string[] args)
    {
    
    
    
            Console.WriteLine("Enter number:");
            int fnum = 0;
            bool chek = Int32.TryParse(Console.ReadLine(),out fnum);            
    
    
            Console.WriteLine("Enter number:");
            int snum = 0;
            chek = Int32.TryParse(Console.ReadLine(),out snum);
    
    
            Console.WriteLine("Enter number:");
            int thnum = 0;
            chek = Int32.TryParse(Console.ReadLine(),out thnum);
    
    
            int[] arr = AddToArr(fnum,snum,thnum);
    
            IOrderedEnumerable<int> oarr = arr.OrderBy(delegate(int s)
            {  
                return s;
            });
    
    
            Console.WriteLine("Here your result:");
    
    
            oarr.ToList().FindAll(delegate(int num) {
    
                Console.WriteLine(num);
    
                return num > 0;
    
            });
    
    
    
    }
    
    
    
    public static int[] AddToArr(params int[] arr) {
    
        return arr;
    }
    

    I hope this will help to you, just change the type

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