C#在循环中填充具有值的数组

时间:2018-10-23 19:28:46

标签: c# arrays loops

我有一个C#控制台应用程序,可以在其中读取外部文本文件。文件的每一行都有用空格分隔的值,例如:

1 -88 30.1
2 -89 30.1

因此,第一行应分为“ 1”,“-88”和“ 30.1”。

我需要做的是填充一个数组(或其他更好的对象),以便它复制每一行。数组每行应具有3个元素。我必须有一个头脑锁定,不要今天解决这个问题。这是我的代码:

string line;
int[] intArray;
intArray = new int[3];
int i = 0;

//Read Input file
using (StreamReader file = new StreamReader("Score_4.dat"))            
{   
    while ((line = file.ReadLine()) != null && line.Length > 10)
    {                    
        line.Trim();
        string[] parts;
        parts = line.Split(' ');
        intArray[0][i] = parts[0];//error: cannot apply indexing
        i++; 
    }
}

在我的代码中,我打算通过遍历数组(或备用对象)的同时构造一个Json对象,对服务器进行一些API调用。

有什么主意吗? 谢谢

5 个答案:

答案 0 :(得分:2)

我将创建一个自定义Item类,然后使用自包含项目填充一个列表,以便于访问和排序。像这样:

 public Class MyItem
 {
     public int first { get; set; }
     public int second { get; set; }
     public float third { get; set; }

     public MyItem(int one, int two, float three)
     {
         this.first = one;
         this.second = two;
         this.third = three;
     }
}

那么您可以做:

List<MyItem> mylist = new List<MyItem>();

,然后在您的循环中:

using (StreamReader file = new StreamReader("Score_4.dat"))            
{   
    while ((line = file.ReadLine()) != null && line.Length > 10)
    {                    
        line.Trim();
        string[] parts;
        parts = line.Split(' ');
        MyItem item = new Item(Int32.Parse(parts[0]),Int32.Parse(parts[1]),Float.Parse(parts[2]));
        mylist.Add(item);
        i++; 
    }
}

答案 1 :(得分:2)

如果只需要将数据传输到JSON,则不需要处理数据的值,只需将其重新格式化为JSON数组即可。

由于您不知道输入文件中的行数,因此使用容量自动扩展的List <>来保存数据,而不是使用数组(您需要知道其大小)更容易。前进。

我获取了您的示例数据,并将其重复了几次后变成了文本文件,并使用了该程序:

static void Main(string[] args)
{
    string src = @"C:\temp\Score_4.dat";
    List<string> dataFromFile = new List<string>();
    using (var sr = new StreamReader(src))
    {
        while (!sr.EndOfStream)
        {
            string thisLine = sr.ReadLine();
            string[] parts = thisLine.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            if (parts.Length == 3)
            {
                string jsonArray = "[" + string.Join(",", parts) + "]";
                dataFromFile.Add(jsonArray);
            }
            else
            {
                /* the line did not have three entries */
                /* Maybe keep a count of the lines processed to give an error message to the user */
            }
        }
    }

    /* Do something with the data... */
    int totalEntries = dataFromFile.Count();
    int maxBatchSize = 50;
    int nBatches = (int)Math.Ceiling((double)totalEntries / maxBatchSize);
    for(int i=0;i<nBatches;i+=1)
    {
        string thisBatchJsonArray = "{\"myData\":[" + string.Join(",", dataFromFile.Skip(i * maxBatchSize).Take(maxBatchSize)) + "]}";
        Console.WriteLine(thisBatchJsonArray);
    }

    Console.ReadLine();
}

获得此输出:

  

{“ myData”:[[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88 ,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[ 1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89, 30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2 ,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1 ],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1, -88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1] ,[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,- 89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1], [2,-89,30.1]]}
  {“ myData”:[[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1] ,[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,- 88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1], [1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1]]}

应易于根据需要调整格式。

答案 2 :(得分:0)

您的int数组是一维数组,但您正尝试像多维数组一样对其建立索引。应该是这样的:

intArray[i] = parts[0]

(但是,对于小数部分,您将需要将其转换为int)

或者,如果要使用多维数组,则必须声明一个。

int[][] intArray = new int[*whatever your expected number of records are*][3]

数组具有静态大小。由于您正在读取文件,并且在文件读取完成之前可能不知道有多少记录,因此我建议根据需要使用诸如“元组列表”或“字典”之类的内容。

通过词典,您可以快速查找记录,而无需使用键值对来对其进行遍历,因此,如果您希望记录与行号匹配,可以执行以下操作:

Dictionary<int, int[]> test = new Dictionary<int, int[]>();
int lineCount = 1;
while ((line = file.ReadLine()) != null && line.Length > 10)
   {
      int[] intArray = new int[3];
      line.Trim();
      string[] parts = line.Split(' ');
      for (int i = 0; i < 3; i++)
          {
               intArray[i] = int.Parse(parts[i]);
          }
      test[lineCount] = intArray;
      lineCount++;

  }

这将使您可以按行数访问值,如下所示:

test[3] = *third line of file*

答案 3 :(得分:0)

由于存在像30.1这样的数字,因此int不适合这样做,它也不能是double[]而是double[][]

string[] lines = File.ReadAllLines("file.txt");
double[][] array = lines.Select(x => s.Split(' ').Select(a => double.Parse(a)).ToArray()).ToArray();

答案 4 :(得分:0)

问题是int数组是一维的。

我的建议是,您可以放置​​一个具有3个属性的类,并在其中填充类列表。最好让类具有与构建JSON所需的相同的属性名称。这样您就可以使用Newtonsoft之类的一些nuget轻松地将该类序列化为JSON,并轻松进行api调用。