【问题标题】:How can I print all the items from the list to the console in C#?如何在 C# 中将列表中的所有项目打印到控制台?
【发布时间】:2022-01-15 11:09:44
【问题描述】:

我正在编写代码来获取输出(从文本文件中读取):“具有姓名、性别、年龄等实例的人员列表”。但是,当我运行代码时,我只得到了文本文件中列表的第一行。这是我的代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Person_Del
{
    class Program
    {
        public static void Main(String[] args)
        {
            Console.SetIn(new StreamReader("data.txt"));
            List<Person> p = new();
            string data = Console.ReadLine();
            Person obj = new();
            obj.SetData(data,"/");
            p.Add(obj);    
                foreach (var ii in p)
                {
                    Console.WriteLine(ii.GetInfo());
                }
        }
    }
    public class Person
    {
        //static methods
        public static void CheckData(string name, string gender, byte age)
        {
            string msg = null;
            if (string.IsNullOrEmpty(name)) msg += "Empty Name";
            if (string.IsNullOrEmpty(gender)) msg += (msg != null ? "; " : "") + "Empty Gender";
            if (age > 125) msg += (msg != null ? "; " : "") + $"Invalid age ({age})";
            if (msg != null) throw new Exception(msg);
        }
        public static (string, string, byte) Parse(string data, string delimiter)
        {
            try
            {
                string[] arr = data.Split(delimiter);
                string name = arr[0].Trim();
                string gender = arr[1].Trim();
                byte age = byte.Parse(arr[2]);
                return (name, gender, age);
            }
            catch (Exception)
            {
                throw new Exception($"Given data \"{data}\" are invalid.");
            }
        }

        //instance fields
        protected string name;
        protected string gender;
        protected byte age;

        //instance methods
        public string GetName() => name;
        public string GetGender() => gender;
        public byte GetAge() => age;

        public void SetData(string name, string gender, byte age)
        {
            Person.CheckData(name, gender, age);
            this.name = name;
            this.gender = gender;
            this.age = age;
        }
        public void SetData(string data, string delimiter)
        {
            (string, string, byte) value = Person.Parse(data, delimiter);
            string name = value.Item1;
            string gender = value.Item2;
            byte age = value.Item3;
            this.SetData(name, gender, age);
        }
        public string GetInfo() => $"Name:{name}, Gender:{gender}, Age:{age}";


        //new instance methods for homework
        public void SetName(string name) => this.name = name;
        public void SetGender(string gender) => this.gender = gender;

        internal bool SetData()
        {
            throw new NotImplementedException();
        }
    }
}

这是我的文本文件(data.txt):

Alice/F/23
David/M/23

注意:我想得到上面两行的输出;然而,我得到的只是第一行“Alice/F/23”。

【问题讨论】:

  • 如果要读取文件,请使用System.IO.File.ReadXXX 方法,而不是将控制台输入附加到附加到文件的流读取器上。混乱的秘诀。至少,做using var sr = new StreamReader("file path here") 然后反复调用sr.ReadLine() - 不要将控制台用作它的支架

标签: c# list foreach


【解决方案1】:

首先将所有行读入一个数组:

    public static void Main(String[] args)
    {
        var lines = File.ReadAllLines("data.txt");
        List<Person> people = new();
        foreach(var line in lines){
          Person p = new();
          p.SetData(line,"/");
          people.Add(obj); 
        }   
        foreach (var person in people )
        {
          Console.WriteLine(person.GetInfo());
        }
    }

通过使用 StreamReader 逐步阅读:

    public static void Main(String[] args)
    {
        using var sr = new StreamReader("data.txt");
        List<Person> people = new();
        while(!sr.EndOfStream)
        {
          var line = sr.ReadLine();
          Person p = new();
          p.SetData(line,"/");
          people.Add(p); 
        }   
        foreach (var person in people)
        {
          Console.WriteLine(person.GetInfo());
        }
    }

您要问的问题最终源于您只调用一次 ReadLine 的事实,但我不建议将 StreamReader 存储在控制台的标准输入中。

我还更好地命名了你的变量;争取有意义的名称 - 对列表和数组等使用复数。短期变量可能相对无意义,例如Person p,但在多个地方使用的长期变量/变量,尝试制作它们,使代码读起来像一本书: foreach(var person in people) 而不是 foreach(var ii in p)

【讨论】:

    猜你喜欢
    • 2022-01-25
    • 1970-01-01
    • 2013-02-10
    • 2011-01-11
    • 2023-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-28
    相关资源
    最近更新 更多