【问题标题】:Adding elements to a C# array向 C# 数组添加元素
【发布时间】:2012-03-23 04:17:02
【问题描述】:

我想以编程方式向 C# 中的字符串数组添加或删除一些元素,但仍保留我之前拥有的项目,有点像 VB 函数ReDim Preserve。

【问题讨论】:

  • 你试过什么?由于它的基本性质,这个问题可能在 3 分钟内有 50 个答案。谷歌也会有同样的帮助。
  • vb 的 redim 保留过去和现在都是邪恶的。你总是总是,无一例外,最好使用集合类型。而且我不会经常做出这样的绝对声明。
  • 减 5 对于这个问题似乎有点苛刻。在从 VBA 迁移到 C# 时,我一直在为这个概念和过渡而苦苦挣扎。

标签: c#


【解决方案1】:

如果您真的不会(或不能)使用泛型集合而不是数组,Array.Resize 是 c# 的 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

【讨论】:

    【解决方案2】:

    明显的建议是改用List<string>,您已经从其他答案中读到过。这绝对是真实开发场景中的最佳方式。

    当然,我想让事情变得更有趣(我的日子就是这样),所以我会直接回答你的问题。

    这里有几个函数可以在string[]...中添加和删除元素...

    string[] Add(string[] array, string newValue){
        int newLength = array.Length + 1;
    
        string[] result = new string[newLength];
    
        for(int i = 0; i < array.Length; i++)
            result[i] = array[i];
    
        result[newLength -1] = newValue;
    
        return result;
    }
    
    string[] RemoveAt(string[] array, int index){
        int newLength = array.Length - 1;
    
        if(newLength < 1)
        {
            return array;//probably want to do some better logic for removing the last element
        }
    
        //this would also be a good time to check for "index out of bounds" and throw an exception or handle some other way
    
        string[] result = new string[newLength];
        int newCounter = 0;
        for(int i = 0; i < array.Length; i++)
        {
            if(i == index)//it is assumed at this point i will match index once only
            {
                continue;
            }
            result[newCounter] = array[i];
            newCounter++;
        }  
    
        return result;
    }
    

    【讨论】:

    • 感谢大家花时间在我的问题上并回答它!!!!你们每个人都对我有用!!!特别感谢你,你的答案就是我要找的那个!!!
    • 请注意,List&lt;T&gt; 在内部的作用与ReDim Preserve 在数组上的作用完全相同。事实上List&lt;T&gt; 将内容存储在一个内部数组中,并在需要时自动调整其大小。这使得 ReDim Preserve 即使在 VB 中也已过时。
    【解决方案3】:

    不要使用数组 - 使用通用的 List&lt;T&gt;,它允许您动态添加项目。

    如果这不是一个选项,您可以使用Array.Copy 或Array.CopyTo 将数组复制到更大的数组中。

    【讨论】:

      【解决方案4】:

      由于数组实现了IEnumerable&lt;T&gt;,你可以使用Concat:

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

      或者更合适的是使用支持内联操作的集合类型。

      【讨论】:

        【解决方案5】:

        使用List&lt;string&gt; 代替string[]。

        列表允许您添加和删除性能良好的项目。

        【讨论】:

          【解决方案6】:

          这个是什么意思:

          List<int> tmpList = intArry.ToList(); tmpList.Add(anyInt); intArry = tmpList.ToArray();

          【讨论】:

            【解决方案7】:

            一个班轮:

                string[] items = new string[] { "a", "b" };
            
                // this adds "c" to the string array:
                items = new List<string>(items) { "c" }.ToArray();      
            

            【讨论】:

              【解决方案8】:

              你应该看看Listobject。列表往往更擅长随心所欲地动态更改。数组没那么多...

              【讨论】:

                【解决方案9】:

                您可以使用通用集合,例如 List

                List<string> list = new List<string>();
                
                // add
                list.Add("element");
                
                // remove
                list.Remove("element");
                

                【讨论】:

                • 从列表中删除元素和从数组中删除元素的等效概念可能是通过RemoveAt 方法,因为它采用索引值。 Remove 删除了可能需要但似乎更难以控制的第一次出现。
                【解决方案10】:

                你可以使用这个sn-p:

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

                希望对你有帮助,换个类型就行了

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 2014-08-03
                  • 1970-01-01
                  • 1970-01-01
                  • 2019-05-26
                  • 2022-01-20
                  • 2011-08-11
                  • 2015-09-02
                  相关资源
                  最近更新 更多