为了账号安全,请及时绑定邮箱和手机立即绑定

使用结构体和列表来存储 csv 文件的部分内容

使用结构体和列表来存储 csv 文件的部分内容

PHP
ABOUTYOU 2024-01-20 21:49:01
因此,我必须在本作业中使用一个结构体,并且需要对一个名为 Country_databas.csv 的 CSV 文件进行排序。到目前为止,我已经制作了该结构体和一个列表,用于处理 CSV 上一行的每个分割。但是,我正在努力将 CSV 的每个拆分添加到其各自的列表中,以便我可以对它们进行排序。编辑:抱歉,我刚刚意识到我错过了 CSV 在线的最后一个分割,即第一行的“Kabul”。我的 CSV 的前 4 行:1. Afghanistan,Asia,652230,25500100,20364000000,Kabul2. Albania,Europe,28748,2821977,12044000000,Tirana3. Algeria,Africa,2381741,38700000,207021000000,Algiers4. Andorra,Europe,468,76098,3222000000,Andorra la Vella代码:namespace CSVFileUtility{  public struct CSVline  {    public List<string> Country;    public List<string> Continent;    public List<int> popualtion;    public List<int> landmass;    public List<long> Bignum;    public CSVline(List<string> Country, List<string> Continent, List<int> popualtion, List<int> landmass, List<long> Bignum)    {      this.Country = Country;      this.Continent = Continent;      this.popualtion = popualtion;      this.landmass = landmass;      this.Bignum = Bignum;    }  }  class Program  {    static void Main(string[] args)    {      string line;      CSVline csv = new CSVline();      using ( StreamReader sr = new StreamReader(@"filepath of csv") )      {        try        {          while ( ( line = sr.ReadLine() ) != null )          {            var values = line.Split(',');            csv.Country.Add(values[1]);          }        }        catch ( Exception ex )        {          Console.WriteLine("The file could not be read {0}", ex);        }      }    }  }}这会导致错误“无法读取文件 System.NullReferenceException:对象引用未设置到对象的实例”,该错误来自行“csv.Country.Add(values[1]);”
查看完整描述

1 回答

?
慕侠2389804

TA贡献1719条经验 获得超6个赞

您的结构错误,您不应在结构中添加列表,结构的每条记录应仅包含一个国家/地区的条目,然后您可以像这样创建结构列表:


public struct CSVline

{

public string Country;

public string Continent;

public int popualtion;

public int landmass;

public long Bignum;


public CSVline(string Country, string Continent, int popualtion, int landmass, long Bignum)

{

    this.Country = Country;

    this.Continent = Continent;

    this.popualtion = popualtion;

    this.landmass = landmass;

    this.Bignum = Bignum;

}



}

那么你可以这样做:


    string line;

    var csv  = new List<CSVline>();

    using (StreamReader sr = new StreamReader(@"filepath of csv"))

    {

        try

        { 

            while ((line = sr.ReadLine()) != null)

            {

                var values = line.Split(',');

                csv.Add(new CSVline(values[0],values[1],values[2],values[3],values[4]));




            }

        }

        catch (Exception ex)

        {

            Console.WriteLine("The file could not be read {0}", ex);

        }

      }


查看完整回答
反对 回复 2024-01-20
  • 1 回答
  • 0 关注
  • 42 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信