亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用結構體和列表來存儲 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 關注
  • 235 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號