逗号分隔的类属性分配问题

时间:2019-01-27 12:23:45

标签: c#

我正在将逗号分隔的文件加载到列表中,这里没有问题。除了最后一段用分号分隔外,我需要将其放入具有属性名称的数组中。在这种情况下,顺序和旋转。下面的代码可以工作,除了为其赋予属性名称。

任何建议将不胜感激。为了避免混乱,我将下面的代码保留为空。

示例CSV文件:Bar001,P02;90

class PartDetail 
{
 public string Description 
 {
  get;
  set;
 }
 public string[] BottomEdge 
 {
  get;
  set;
 }


 public class SpecificDetails << < I want to use this class to specify the property name. {
  public string Sequence 
  {
   get;
   set;
  }
  public string Rotation 
  {
   get;
   set;
  }
 }

 public PartDetail(string line) 
 {
  string[] parts = line.Split(',');
  this.Description = parts[0];
  this.BottomEdge = parts[1].Split(';'); << It 's here where I am struggling.
 }
}

3 个答案:

答案 0 :(得分:1)

我认为这可以解决问题

class PartDetail 
{
 ....
 //create an instance of your SpecificDetails class
 SpecificDetails Details = new SpecificDetails();
 ...
 public PartDetail(string line) 
 {
  string[] parts = line.Split(',');
  this.Description = parts[0];
  this.BottomEdge = parts[1].Split(';'); 

  //assign the value to the properties of the "Details" instance
  this.Details.Sequence = this.BottomEdge[0];
  this.Details.Rotation = this.BottomEdge[1];
 }
}

答案 1 :(得分:0)

使用line.Split(new char[]{ ',', ';'})并仅选择返回数组的最后一个索引作为逻辑的结束段。

答案 2 :(得分:0)

点网具有内置的CSV解析器,因此无需滚动自己的{https://coding.abel.nu/2012/06/built-in-net-csv-parser/

using (TextFieldParser parser = new TextFieldParser(path))
{
parser.CommentTokens = new string[] { "#" };
parser.SetDelimiters(new string[] { ";" });
parser.HasFieldsEnclosedInQuotes = true;

// Skip over header line.
parser.ReadLine();

while (!parser.EndOfData)
{
    string[] fields = parser.ReadFields();

}
}

解析后,剩下的分号问题很容易用string.Split解决。