从对象写入数据

时间:2015-09-23 15:43:41

标签: c# object

让我说我有一个班级

class Data
{
    public string Name { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

    public Data(string name, string lastname, int age)
    {
        Name = name;
        LastName = name;
        Age = age;
    }
}

我想得到一个人的年龄,如果它是< 18然后将所有数据打印到Kids.csv,否则我希望它打印到Adults.csv

我知道这很简单,我设法做到了,但老师说我的代码看起来不像客观编程。他告诉我,我需要使用方法返回数组,并创建其他方法将数组写入文件或其他东西。

1 个答案:

答案 0 :(得分:1)

你可能会看一下这个基本的东西来建模你的方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Data
{
    public class DataList
    {
        public List<Data> lData { get; set; }
        public bool WriteToCSV(string strPath)
        {
            bool ret = false;

            try
            {
                List<Data> lKids = this.lData.Where(x => x.Age < 18).ToList();
                List<Data> lAdults = this.lData.Where(x => x.Age >= 18).ToList();
                if (lKids.Count > 0)
                {
                    string strFilePath = strPath + "Kids.csv";
                    using (StreamWriter sw = new StreamWriter(strFilePath))
                    {
                        foreach (Data p in lKids)
                        {
                            string strRow = (char)34 + p.Name + (char)34 + "," + (char)34 + p.LastName + (char)34 + "," + p.Age.ToString();
                            sw.WriteLine(strRow);
                        }
                    }
                    ret = true;
                }
                if (lAdults.Count > 0)
                {
                    string strFilePath = strPath + "Adults.csv";
                    using (StreamWriter sw = new StreamWriter(strFilePath))
                    {
                        foreach (Data p in lAdults)
                        {
                            string strRow = (char)34 + p.Name + (char)34 + "," + (char)34 + p.LastName + (char)34 + "," + p.Age.ToString();
                            sw.WriteLine(strRow);
                        }
                    }
                    ret = true;
                }
            }
            catch
            {
                ret = false;
            }
            return ret;
        }
    }
    public class Data
    {
        public string Name { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }

        public Data(string name, string lastname, int age)
        {
            Name = name;
            LastName = name;
            Age = age;
        }
    }
}