【问题标题】:Adding values to a C# array向 C# 数组添加值
【发布时间】:2010-09-17 04:45:54
【问题描述】:

这可能是一个非常简单的 - 我从 C# 开始,需要向数组添加值,例如:

int[] terms;

for(int runs = 0; runs < 400; runs++)
{
    terms[] = runs;
}

对于那些使用过 PHP 的人,这是我在 C# 中尝试做的事情:

$arr = array();
for ($i = 0; $i < 10; $i++) {
    $arr[] = $i;
}

【问题讨论】:

  • 不应该'terms[] = value;'是 'terms[] = runs;'?
  • 在 C# 中,数组大小一旦创建就无法更改。如果您想要类似数组但能够添加/删除元素的东西,请使用 List().
  • @KamranBigdely 并非如此,您可以将数组用作 IList 并使用 LinQ 重新分配值(使用 System.Linq): terms= terms.Append(21).ToArray();
  • @Leandro:实际上每次运行时都会创建一个新数组 --> terms= terms.Append(21).ToArray();
  • 是的,然后在分配中销毁,那又怎样?

标签: c# arrays


【解决方案1】:

你可以这样做-

int[] terms = new int[400];
for (int runs = 0; runs < 400; runs++)
{
    terms[runs] = value;
}

或者,您可以使用列表 - 列表的优势在于,您在实例化列表时不需要知道数组大小。

List<int> termsList = new List<int>();
for (int runs = 0; runs < 400; runs++)
{
    termsList.Add(value);
}

// You can convert it back to an array if you would like to
int[] terms = termsList.ToArray();

编辑: a) for loops on List<T> are a bit more than 2 times cheaper than foreach loops on List<T>, b) Looping on array is around 2 times cheaper than looping on List<T>, c) looping on array using for is 5 times cheaper than looping on List<T> using foreach (which most of us do).

【讨论】:

  • 在这种情况下使用列表有什么好处?
  • @PhillHealey 在创建阵列之前,您不必“知道”阵列可能会变得多大。如您所见,在这些示例中,OP 必须将值放入“new int[400]” - 但对于列表,他不必这样做。
  • 代码的第一位不会是什么,因为值没有在任何地方定义。 -_-
  • 为什么说ARRAY需要有大小???就做new int[]{} !!!!!!
  • @T.Todua 如果您按照您的建议创建一个空数组,然后尝试访问它不存在的索引来设置值,您将在运行代码后立即获得一个 OutOfRangeException .数组需要使用您要使用的大小进行初始化,它们在开始时保留所有空间,女巫使它们非常快,但无法调整它们的大小。
【解决方案2】:

使用Linq 的方法Concat 让这个变得简单

int[] array = new int[] { 3, 4 };

array = array.Concat(new int[] { 2 }).ToArray();

结果 3,4,2

【讨论】:

  • 该方法将使向数组中添加 400 个项目创建一个具有更多空间的数组副本,并将所有元素移动到新数组中,40000 次。所以不推荐性能方面。
【解决方案3】:

如果您使用 C# 3 编写,则可以使用单行代码:

int[] terms = Enumerable.Range(0, 400).ToArray();

此代码 sn-p 假定您在文件顶部有一个用于 System.Linq 的 using 指令。

另一方面,如果您正在寻找可以动态调整大小的东西,就像 PHP 的情况一样(我从未真正学习过),那么您可能想要使用 List 而不是整数 []。 代码如下所示:

List<int> terms = Enumerable.Range(0, 400).ToList();

但是请注意,您不能通过将 terms[400] 设置为一个值来简单地添加第 401 个元素。相反,您需要调用 Add(),如下所示:

terms.Add(1337);

【讨论】:

    【解决方案4】:

    此处提供了有关如何使用数组执行此操作的答案。

    但是,C# 有一个非常方便的东西,叫做 System.Collections :)

    集合是使用数组的花哨替代方案,尽管其中许多在内部使用数组。

    例如,C# 有一个名为 List 的集合,其功能与 PHP 数组非常相似。

    using System.Collections.Generic;
    
    // Create a List, and it can only contain integers.
    List<int> list = new List<int>();
    
    for (int i = 0; i < 400; i++)
    {
       list.Add(i);
    }
    

    【讨论】:

    • 用于检索列表元素:int a = list[i];
    【解决方案5】:

    到 2019 年,您可以在一行中使用 AppendPrependLinQ

    using System.Linq;
    

    然后:

    terms= terms.Append(21).ToArray();
    

    【讨论】:

    • 使用列表通常是一个更好的主意,但如果真的想使用数组,这是最简单的方法!
    • @XouDo 100% 同意
    • +1 但如果您非常关心性能,请不要使用 Linq,如果您想要更短的更好的可读性和可维护性的代码,请使用它。
    • @volkit 为了提高性能,您必须使用数组,而不是列表。
    【解决方案6】:

    正如其他人所描述的那样,使用 List 作为中介是最简单的方法,但由于您的输入是一个数组,而且您不只是想将数据保存在 List 中,我想您可能会担心性能。

    最有效的方法可能是分配一个新数组,然后使用 Array.Copy 或 Array.CopyTo。如果您只想在列表末尾添加一个项目,这并不难:

    public static T[] Add<T>(this T[] target, T item)
    {
        if (target == null)
        {
            //TODO: Return null or throw ArgumentNullException;
        }
        T[] result = new T[target.Length + 1];
        target.CopyTo(result, 0);
        result[target.Length] = item;
        return result;
    }
    

    如果需要,我还可以发布将目标索引作为输入的插入扩展方法的代码。稍微复杂一点,使用静态方法Array.Copy 1-2次。

    【讨论】:

    • 创建一个列表会更好,性能明智,将其填满,然后在最后复制到数组,这样您就不会创建和复制数组超过 400 次
    【解决方案7】:

    基于 Thracx 的回答(我没有足够的分数来回答):

    public static T[] Add<T>(this T[] target, params T[] items)
        {
            // Validate the parameters
            if (target == null) {
                target = new T[] { };
            }
            if (items== null) {
                items = new T[] { };
            }
    
            // Join the arrays
            T[] result = new T[target.Length + items.Length];
            target.CopyTo(result, 0);
            items.CopyTo(result, target.Length);
            return result;
        }
    

    这允许向数组中添加多个项目,或者只是传递一个数组作为参数来连接两个数组。

    【讨论】:

      【解决方案8】:

      你必须先分配数组:

      int [] terms = new int[400]; // allocate an array of 400 ints
      for(int runs = 0; runs < terms.Length; runs++) // Use Length property rather than the 400 magic number again
      {
          terms[runs] = value;
      }
      

      【讨论】:

        【解决方案9】:
        int ArraySize = 400;
        
        int[] terms = new int[ArraySize];
        
        
        for(int runs = 0; runs < ArraySize; runs++)
        {
        
            terms[runs] = runs;
        
        }
        

        这就是我的编码方式。

        【讨论】:

          【解决方案10】:

          C# 数组是固定长度的并且总是被索引的。采用 Motti 的解决方案:

          int [] terms = new int[400];
          for(int runs = 0; runs < 400; runs++)
          {
              terms[runs] = value;
          }
          

          请注意,此数组是一个密集数组,是一个 400 字节的连续块,您可以在其中放置东西。如果您想要一个动态大小的数组,请使用 List.

          List<int> terms = new List<int>();
          for(int runs = 0; runs < 400; runs ++)
          {
              terms.Add(runs);
          }
          

          int[] 和 List 都不是关联数组——这将是 C# 中的 Dictionary。数组和列表都是密集的。

          【讨论】:

            【解决方案11】:

            您不能简单地将元素添加到数组中。您可以将元素设置在给定位置,如 fallen888 所述,但我建议改用List&lt;int&gt;Collection&lt;int&gt;,如果需要将其转换为数组,请使用ToArray()

            【讨论】:

              【解决方案12】:

              如果你真的需要一个数组,下面可能是最简单的:

              using System.Collections.Generic;
              
              // Create a List, and it can only contain integers.
              List<int> list = new List<int>();
              
              for (int i = 0; i < 400; i++)
              {
                 list.Add(i);
              }
              
              int [] terms = list.ToArray();
              

              【讨论】:

                【解决方案13】:
                int[] terms = new int[10]; //create 10 empty index in array terms
                
                //fill value = 400 for every index (run) in the array
                //terms.Length is the total length of the array, it is equal to 10 in this case 
                for (int run = 0; run < terms.Length; run++) 
                {
                    terms[run] = 400;
                }
                
                //print value from each of the index
                for (int run = 0; run < terms.Length; run++)
                {
                    Console.WriteLine("Value in index {0}:\t{1}",run, terms[run]);
                }
                
                Console.ReadLine();
                

                /*输出:

                索引 0 中的值:400
                索引 1 中的值:400
                索引 2 中的值:400
                索引 3 中的值:400
                索引 4 中的值:400
                索引 5 中的值:400
                索引 6 中的值:400
                索引 7 中的值:400
                索引 8 中的值:400
                索引 9 中的值:400
                */

                【讨论】:

                • 你能解释一下这个解决方案吗?
                • Rune,我刚刚在源代码中包含了注释> 希望它能回答你的问题。
                【解决方案14】:

                我会为另一个变体添加这个。我更喜欢这种类型的函数式编码线。

                Enumerable.Range(0, 400).Select(x => x).ToArray();
                

                【讨论】:

                  【解决方案15】:

                  一种方法是通过 LINQ 填充数组

                  如果你想用一个元素填充数组 你可以简单地写

                  string[] arrayToBeFilled;
                  arrayToBeFilled= arrayToBeFilled.Append("str").ToArray();
                  

                  此外,如果你想用多个元素填充一个数组,你可以使用 循环中的前一个代码

                  //the array you want to fill values in
                  string[] arrayToBeFilled;
                  //list of values that you want to fill inside an array
                  List<string> listToFill = new List<string> { "a1", "a2", "a3" };
                  //looping through list to start filling the array
                  
                  foreach (string str in listToFill){
                  // here are the LINQ extensions
                  arrayToBeFilled= arrayToBeFilled.Append(str).ToArray();
                  }
                  
                  

                  【讨论】:

                    【解决方案16】:

                    如果您不知道数组的大小或已有要添加的数组。你可以通过两种方式来解决这个问题。第一个是使用通用的List&lt;T&gt;: 为此,您需要将数组转换为 var termsList = terms.ToList(); 并使用 Add 方法。然后在完成后使用var terms = termsList.ToArray(); 方法转换回数组。

                    var terms = default(int[]);
                    var termsList = terms == null ? new List<int>() : terms.ToList();
                    
                    for(var i = 0; i < 400; i++)
                        termsList.Add(i);
                    
                    terms = termsList.ToArray();
                    

                    第二种方法是调整当前数组的大小:

                    var terms = default(int[]);
                    
                    for(var i = 0; i < 400; i++)
                    {
                        if(terms == null)
                            terms = new int[1];
                        else    
                            Array.Resize<int>(ref terms, terms.Length + 1);
                        
                        terms[terms.Length - 1] = i;
                    }
                    

                    如果您使用的是 .NET 3.5 Array.Add(...);

                    这两种方法都可以让您动态地执行此操作。如果您要添加很多项目,那么只需使用List&lt;T&gt;。如果它只是几个项目,那么调整数组大小将具有更好的性能。这是因为您在创建 List&lt;T&gt; 对象时受到的影响更大。

                    单位:

                    3 项

                    数组调整时间:6

                    列表添加时间:16

                    400 项

                    数组调整时间:305

                    列表添加时间:20

                    【讨论】:

                      【解决方案17】:

                      只是一种不同的方法:

                      int runs = 0; 
                      bool batting = true; 
                      string scorecard;
                      
                      while (batting = runs < 400)
                          scorecard += "!" + runs++;
                      
                      return scorecard.Split("!");
                      

                      【讨论】:

                      • 虽然有点新奇,但这是在执行 lot 的字符串连接,然后执行大型枚举操作!不是最高效的,也不是最容易理解/可读的方式。
                      • @Ali Humayun 你真的打算使用赋值运算符= 而不是比较运算符吗?您可以省略战斗变量并使用runs &lt; 400 来控制循环。
                      • 只是练习编程双关语
                      【解决方案18】:

                      您不能直接执行此操作。但是,您可以使用 Linq 来执行此操作:

                      List<int> termsLst=new List<int>();
                      for (int runs = 0; runs < 400; runs++)
                      {
                          termsLst.Add(runs);
                      }
                      int[] terms = termsLst.ToArray();
                      

                      如果数组 terms 一开始不是空的,你可以先把它转换成 List 然后再做你的 stuf。喜欢:

                          List<int> termsLst = terms.ToList();
                          for (int runs = 0; runs < 400; runs++)
                          {
                              termsLst.Add(runs);
                          }
                          terms = termsLst.ToArray();
                      

                      注意:不要错过在文件开头添加“using System.Linq;”。

                      【讨论】:

                        【解决方案19】:

                        这对我来说似乎少了很多麻烦:

                        var usageList = usageArray.ToList();
                        usageList.Add("newstuff");
                        usageArray = usageList.ToArray();
                        

                        【讨论】:

                          【解决方案20】:

                          Array Push Example

                          public void ArrayPush<T>(ref T[] table, object value)
                          {
                              Array.Resize(ref table, table.Length + 1); // Resizing the array for the cloned length (+-) (+1)
                              table.SetValue(value, table.Length - 1); // Setting the value for the new element
                          }
                          

                          【讨论】:

                            【解决方案21】:
                            int[] terms = new int[400];
                            
                            for(int runs = 0; runs < 400; runs++)
                            {
                                terms[runs] = value;
                            }
                            

                            【讨论】:

                              【解决方案22】:
                                       static void Main(string[] args)
                                      {
                                          int[] arrayname = new int[5];/*arrayname is an array of 5 integer [5] mean in array [0],[1],[2],[3],[4],[5] because array starts with zero*/
                                          int i, j;
                              
                              
                                        /*initialize elements of array arrayname*/
                                          for (i = 0; i < 5; i++)
                                          {
                                              arrayname[i] = i + 100;
                                          }
                              
                                           /*output each array element value*/
                                          for (j = 0; j < 5; j++)
                                          {
                                              Console.WriteLine("Element and output value [{0}]={1}",j,arrayname[j]);
                                          }
                                          Console.ReadKey();/*Obtains the next character or function key pressed by the user.
                                                              The pressed key is displayed in the console window.*/
                                      }
                              

                              【讨论】:

                                【解决方案23】:
                                            /*arrayname is an array of 5 integer*/
                                            int[] arrayname = new int[5];
                                            int i, j;
                                            /*initialize elements of array arrayname*/
                                            for (i = 0; i < 5; i++)
                                            {
                                                arrayname[i] = i + 100;
                                            }
                                

                                【讨论】:

                                  【解决方案24】:

                                  使用 C# 将列表值添加到字符串数组而不使用 ToArray() 方法

                                          List<string> list = new List<string>();
                                          list.Add("one");
                                          list.Add("two");
                                          list.Add("three");
                                          list.Add("four");
                                          list.Add("five");
                                          string[] values = new string[list.Count];//assigning the count for array
                                          for(int i=0;i<list.Count;i++)
                                          {
                                              values[i] = list[i].ToString();
                                          }
                                  

                                  值数组的输出包含:

                                  一个

                                  两个

                                  三个

                                  四个

                                  五个

                                  【讨论】:

                                    【解决方案25】:

                                    您可以通过列表来做到这一点。这是怎么回事

                                    List<string> info = new List<string>();
                                    info.Add("finally worked");
                                    

                                    如果你需要返回这个数组做

                                    return info.ToArray();
                                    

                                    【讨论】:

                                      猜你喜欢
                                      • 2020-03-28
                                      • 1970-01-01
                                      • 2017-03-14
                                      • 1970-01-01
                                      • 1970-01-01
                                      • 1970-01-01
                                      • 2023-04-10
                                      • 1970-01-01
                                      • 1970-01-01
                                      相关资源
                                      最近更新 更多