C#在特定位置用txt文件中的对象填充2D数组

C#在特定位置用txt文件中的对象填充2D数组,c#,C#,我试图用我电脑里的txt文件填充一个2D数组 我试过用两种不同的方法来做这件事,但都没有成功 使用以下代码在文件中保存对象位置号 for (int row = 0; row < 100; row++) { for (int col = 0; col < 2; col++) { if (cpp[row, col] == null)

我试图用我电脑里的txt文件填充一个2D数组

我试过用两种不同的方法来做这件事,但都没有成功

  • 使用以下代码在文件中保存对象位置号

                 for (int row = 0; row < 100; row++)
             {
                 for (int col = 0; col < 2; col++)
                 {
                     if (cpp[row, col] == null)
                     {
                         break;
                     }
                     else
                     {
                         if (cpp[row, col] == null) continue;
                         save.WriteLine(string.Format("{0}, {1}, {2}, {3}", row + 1, cpp[row, col].RegNumber, cpp[row, col].VehicleTypes, cpp[row, col].TimeOfArrival));
                     }
                 }
             }
    
    我还没有得到任何与加载功能,我将感谢任何帮助,我可以得到这个。我需要将文件加载到我的2D数组中,并且必须将对象指定到与以前相同的位置

    加载函数的唯一代码是这样的

    string[] lines = File.ReadAllLines("CarParkPrague.txt");
                var vehicles = new List<Vehicle>();
                {
                    foreach (var line in lines)
                    {
                        var values = line.Split(",");
                        Enum.TryParse(values[1], out VehicleType type);
                        var time = DateTime.Parse(values[2]);
                        vehicles.Add(new Vehicle(values[0], type, time)); 
                        
                    }
                }
    
    string[]lines=File.ReadAllLines(“CarParkPrague.txt”);
    var车辆=新列表();
    {
    foreach(行中的var行)
    {
    var值=行分割(“,”);
    Enum.TryParse(值[1],out VehicleType类型);
    var time=DateTime.Parse(值[2]);
    车辆。添加(新车(值[0],类型,时间));
    }
    }
    
    文本文件行示例=AAA111,CAR,2020-10-11 14:19:04 或者保存位置=1,AAA111,CAR,2020-10-11 14:19:04 可以是任何一个,这是最简单的

    这是一种有效的测试方法,但它将车辆保存在阵列中第一个最佳可用位置,因此它并不完全正确。在这种情况下,保存的文本文件没有位置号。看起来像上面的第一个例子

    static void LoadTestFile() //Loads the array using the test file which is filled with examples.
        {
            string[] lines = File.ReadAllLines("testfile.txt");
            var vehicles = new List<Vehicle>();
    
            foreach (var line in lines)
            {
                var values = line.Split(",");
                Enum.TryParse(values[1], out VehicleType type);
                var time = DateTime.Parse(values[2]);
                vehicles.Add(new Vehicle(values[0], type, time));
            }
    
            int counter = 0;
            for (int i = 0; i < 100; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    if (counter >= vehicles.Count)
                        break;
    
                    if (cpp[i, 0] != null)
                    {
                        if (cpp[i, 0].VehicleTypes == VehicleType.CAR)
                        {
                            continue;
                        }
                    }
    
                    if (vehicles[counter].VehicleTypes == VehicleType.CAR)
                    {
                        cpp[i, j] = vehicles[counter++];
                    }
                    else
                    {
                        cpp[i, j] = vehicles[counter++];
                    }
                }
            }
    
    static void LoadTestFile()//使用充满示例的测试文件加载数组。
    {
    string[]lines=File.ReadAllLines(“testfile.txt”);
    var车辆=新列表();
    foreach(行中的var行)
    {
    var值=行分割(“,”);
    Enum.TryParse(值[1],out VehicleType类型);
    var time=DateTime.Parse(值[2]);
    车辆。添加(新车(值[0],类型,时间));
    }
    int计数器=0;
    对于(int i=0;i<100;i++)
    {
    对于(int j=0;j<2;j++)
    {
    如果(计数器>=车辆计数)
    打破
    if(cpp[i,0]!=null)
    {
    if(cpp[i,0].VehicleTypes==VehicleType.CAR)
    {
    继续;
    }
    }
    if(车辆[计数器].VehicleTypes==VehicleType.CAR)
    {
    cpp[i,j]=车辆[计数器++];
    }
    其他的
    {
    cpp[i,j]=车辆[计数器++];
    }
    }
    }
    
    如果你有空行,你的加载功能会崩溃,因此我不太相信读取一个打开空行的文件是有效的。不过,它的最大问题是,如果它遇到空行,它不会做任何事情,而实际上它应该在列表中的该位置放置一辆空白(空)车辆

    如果车辆为空,则保存空行,并以固定格式保存日期:

            foreach (var temp in cpp)
            {
                if (temp == null) 
                    save.WriteLine();
                else
                    save.WriteLine("{{0},{1},{2}", temp.RegNumber, temp.VehicleTypes, temp.TimeOfArrival.ToString("yyyyMMddHHmmss"));
            }
    
    加载,通过在该位置放置无车辆(空)来满足空白行:

            string[] lines = File.ReadAllLines("CarParkPrague.txt");
            var vehicles = new List<Vehicle>();
            
            foreach (var line in lines)
            {
                if(string.IsNullOrWhiteSpace(line))
                { 
                    vehicles.Add(null);
                    continue;
                }
                var values = line.Split(",");
                Enum.TryParse(values[1], out VehicleType type); //should really test this with an if
                var time = DateTime.ParseExact(values[2], "yyyyMMddHHmmss", null);
                vehicles.Add(new Vehicle(values[0], type, time)); 
                    
            }
        }
    
    string[]lines=File.ReadAllLines(“CarParkPrague.txt”);
    var车辆=新列表();
    foreach(行中的var行)
    {
    if(string.IsNullOrWhiteSpace(行))
    { 
    车辆。添加(空);
    继续;
    }
    var值=行分割(“,”);
    TryParse(值[1],out-VehicleType);//应该使用if来测试这一点
    var time=DateTime.ParseExact(值[2],“yyyyymmddhhmmss”,null);
    车辆。添加(新车(值[0],类型,时间));
    }
    }
    
    希望您能看到“如果停车位为空,则车辆为空,并且在保存过程中变为空行”如何在加载时转换回“如果该行为空,则通过将空车辆放在此处,将空间标记为空”

    编辑;由于您似乎拥有固定数量的停车位,并且使用null表示空,因此拥有一个类似列表的集合(动态调整大小以适应内容)可能并不理想。切换到使用表示停车场大小的数组:

        string[] lines = File.ReadAllLines("CarParkPrague.txt");
        var vehicles = new Vehicle[100];
        
        for (int i = 0; i < lines.Length && i < vehicles.Length; i++)
        {
            var line = lines[i];
    
            if(string.IsNullOrWhiteSpace(line))
                continue;
            
            var values = line.Split(",");
            Enum.TryParse(values[1], out VehicleType type); //should really test this with an if
            var time = DateTime.ParseExact(values[2], "yyyyMMddHHmmss", null);
            vehicles[i] = new Vehicle(values[0], type, time); 
                
        }
    }
    
    string[]lines=File.ReadAllLines(“CarParkPrague.txt”);
    var车辆=新车[100];
    对于(int i=0;i

    不要忘记,加载方法中的
    车辆
    应分配给保存方法中的
    cpp
    所代表的相同变量。实际上,您应该在这两个方法中使用相同的类范围变量

    让我们从一些非常简单的事情开始——镜像save和load方法。唯一需要添加的是数组的维度:

    var rowCount = cpp.GetLength(0);
    var colCount = cpp.GetLength(1);
    
    save.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0},{1}", rowCount, colCount));
    for (var row = 0; row < rowCount; row++)
    {
      for (var col = 0; col < colCount; col++)
      {
        if (cpp[row, col] == null) save.WriteLine();
        else save.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0},{1},{2}", cpp[row, col].RegNumber, cpp[row, col].VehicleTypes, cpp[row, col].TimeOfArrival));
      }
    }
    
    var rowCount=cpp.GetLength(0);
    var colCount=cpp.GetLength(1);
    save.WriteLine(string.Format(CultureInfo.InvariantCulture,“{0},{1}”,rowCount,colCount));
    对于(变量行=0;行<行计数;行++)
    {
    for(var col=0;col
    要读取这种非常直接的文件格式,请反向执行相同的操作:

    using (var sr = new StreamReader("CarParkPrague.txt"))
    {
      var dimensions = sr.ReadLine()?.Split(',');
    
      if (dimensions == null 
          || !int.TryParse(dimensions[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out var rowCount) 
          || !int.TryParse(dimensions[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var colCount)
         )
        throw new Exception("Invalid dimensions.");
    
      var cpp = new Vehicle[rowCount, colCount];
    
      for (var row = 0; row < rowCount; row++)
      {
        for (var col = 0; col < colCount; col++)
        {
          if (!(sr.ReadLine() is {} line) throw new Exception("Unexpected end of file.");
          if (string.IsNullOrWhitespace(line)) continue;
    
          var values = line.Split(",");
          if (!Enum.TryParse(values[1], out var vehicleType)) throw new Exception($"Unexpected vehicle type '{values[1]}'.");
          if (!DateTime.TryParse(values[2], CultureInfo.InvariantCulture, DateTimeStyles.None, out var dateTime) throw new Exception($"Invalid time '{values[2]}'.");
    
          cpp[row, col] = new Vehicle(values[0], type, time); 
        }
      }
    }
    
    使用(var sr=new StreamReader(“CarParkPrague.txt”))
    {
    变量维度=sr.ReadLine()?.Split(',');
    如果(维度==null
    ||!int.试试看
    
    using (var sr = new StreamReader("CarParkPrague.txt"))
    {
      var dimensions = sr.ReadLine()?.Split(',');
    
      if (dimensions == null 
          || !int.TryParse(dimensions[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out var rowCount) 
          || !int.TryParse(dimensions[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var colCount)
         )
        throw new Exception("Invalid dimensions.");
    
      var cpp = new Vehicle[rowCount, colCount];
    
      for (var row = 0; row < rowCount; row++)
      {
        for (var col = 0; col < colCount; col++)
        {
          if (!(sr.ReadLine() is {} line) throw new Exception("Unexpected end of file.");
          if (string.IsNullOrWhitespace(line)) continue;
    
          var values = line.Split(",");
          if (!Enum.TryParse(values[1], out var vehicleType)) throw new Exception($"Unexpected vehicle type '{values[1]}'.");
          if (!DateTime.TryParse(values[2], CultureInfo.InvariantCulture, DateTimeStyles.None, out var dateTime) throw new Exception($"Invalid time '{values[2]}'.");
    
          cpp[row, col] = new Vehicle(values[0], type, time); 
        }
      }
    }
    
     static void SaveFile() //Saves the current array using streamwriter.
        {
            Console.Clear();
            StreamWriter save = new StreamWriter("CarParkPrague.txt");
            using (save)
            {
         
                foreach (var temp in cpp)
                {
                    if (temp == null) save.WriteLine();
                    else
                    save.WriteLine("{0},{1},{2}", temp.RegNumber, temp.VehicleTypes, temp.TimeOfArrival);
                }
            }
            Console.WriteLine("File saved succesfully");
            Console.WriteLine("----------------------------------------------------------------");
        }
    
    
    static void LoadFile() //Loads the array using the saved file.
        {
            try
            {
                string[] lines = File.ReadAllLines("CarParkPrague.txt");
                var vehicles = new List<Vehicle>();
                {
                    foreach (var line in lines)
                    {
                        if (string.IsNullOrWhiteSpace(line))
                        {
                            vehicles.Add(null);
                            continue;
                        }
                        var values = line.Split(",");
                        Enum.TryParse(values[1], out VehicleType type);
                        var time = DateTime.Parse(values[2]);
                        vehicles.Add(new Vehicle(values[0], type, time)); 
                        
                    }
                }
                int counter = 0;
                for (int i = 0; i < 100; i++)
                {
                    for (int j = 0; j < 2; j++)
                    {
    
                        if (vehicles[counter] == null)
                        {
                            cpp[i, j] = vehicles[counter++];
                        }
                       else if (vehicles[counter] != null)
                        {
                            cpp[i, j] = vehicles[counter++];
                        }
                    }
                }
            }
            catch (FileNotFoundException ex)
            {
                Console.WriteLine(ex);
                Console.WriteLine("File could not be found. Please make sure there is a file named (CarParkPrague.txt) in your folder.");
            }
            Console.Clear();
            Console.WriteLine("File have been loaded succesfully");
            Console.WriteLine("----------------------------------------------------------------");
        }