【问题标题】:File input and sorting into array for further organization文件输入和排序成数组以便进一步组织
【发布时间】:2023-03-06 17:59:01
【问题描述】:

我正在设计一个程序,它将接受一个文件输入,在程序的情况下,一个人口普查文件有 4 个不同的输入 age, gender, marital status, and district

我的问题是

  • 我如何准确地获取输入并将它们排序为整数(年龄和地区)和字符串(婚姻状况和性别)数据类型的数组
  • 如何使用它们来计算每个有多少?

任何建议都会有所帮助!我知道如何读取文件并使用 input.Split(',') 分隔信息,以便在有逗号时进行分隔,但是,我在循环时遇到问题,因此它不会不必要地重复循环。

【问题讨论】:

    标签: c# arrays loops sorting


    【解决方案1】:

    你可以开始做这样的事情,这段代码使用Linq

    var records = File.ReadAllLines(filepath) // read all lines
        .Select(line=> line.Split(','))       //  Process each line one by one and split.
        .Select(s=> new                       // Convert to (anonymous)object with properties. 
        {
            Age = int.Parse(s[0]),
            Gender= s[1],
            MaritalStatus,= s[2],  
            Status= s[3],
            District = int.Parse(s[4]),  
        }).ToList();
    

    现在您可以使用

    访问每条记录
    foreach(var record in records)
    {
        // logic
        Console.WriteLine(record);
    }
    

    Count 使用

    int count = records.Count();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-07
      • 1970-01-01
      • 2017-07-25
      • 1970-01-01
      • 2020-06-11
      • 1970-01-01
      • 1970-01-01
      • 2012-01-17
      相关资源
      最近更新 更多