由于字符串解析问题而覆盖类对象

时间:2013-09-13 19:17:06

标签: c# list class object text-files

我正在尝试读取固定宽度的文本文件并将每个元素存储到类对象中。需要检查文本文件中的每一行,以确定必须执行哪种解析操作。每行1000和1001需要以不同方式解析,行1002-1004使用相同的解析操作。我正在读取文件并正确解析,但是当我向类对象添加元素时,对象会在每个“if”语句中被覆盖。然后,当对象添加到列表时,列表包含空行。我觉得我采取了错误的做法。我是C#的新手,如果有人回答我会道歉,但经过几个小时的搜索,我找不到解决方案。下面是文本文件和代码。

1000 AttributeOne AttributeTwo
1001 123456.000000属性四 1002 1234.0 2345.0 3456.0 1003 1234.0 2345.0 3456.0 1004 1234.0 2345.0 3456.0 1000 AttributeOne AttributeTwo
1001 456789.000000属性四 1002 1234.0 2345.0 3456.0 1003 1234.0 2345.0 3456.0 1004 1234.0 2345.0 3456.0 1000 AttributeOne AttributeTwo
1001 234567.000000 AttributeFour
1002 1234.0 2345.0 3456.0 1003 1234.0 2345.0 3456.0 1004 1234.0 2345.0 3456.0 1000 AttributeOne AttributeTwo
1001 345678.000000 AttributeFour
1002 1234.0 2345.0 3456.0 1003 1234.0 2345.0 3456.0 1004 1234.0 2345.0 3456.0

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text.RegularExpressions;
namespace list_question
{    
    public class someObject
    {
        //Line 1
        public int Line1_ID;
        public string Line1_Attribute1;
        public string Line1_Attribute2;
        //Line 2
        public int Line2_ID;
        public decimal Line2_Attribute3;
        public string Line2_Attribute4;
        //Line 3
        public int Line3_ID;
        public decimal data_pos1;
        public decimal data_pos2;
        public decimal data_pos3;        
    }

    class Program
    {
        static void Main(string[] args)
        {
            string filepathRead = @"C:\Users\user1\Desktop\SampleFile.txt";
            List<someObject> somObList = new List<someObject>();
            try
            {
                FileStream fs = new FileStream(filepathRead, FileMode.Open, FileAccess.Read);
                StreamReader reader = new StreamReader(fs);                               
                while (!reader.EndOfStream) 
                {                         
                    string line = reader.ReadLine();
                    if ((line.Substring(0, 4) == "1000"))
                    {
                        string[] strArrFields1 = Regex.Split(line, @"(.{6})" + "(.{14})" + "(.{20})").Where(s => !string.IsNullOrEmpty(s)).ToArray();
                        someObject obj_1 = new someObject();                        
                        obj_1.Line1_ID = int.Parse(strArrFields1[0].TrimEnd(' '));
                        obj_1.Line1_Attribute1 = strArrFields1[1].TrimEnd(' ');
                        obj_1.Line1_Attribute2 = strArrFields1[2].TrimEnd(' ');
                        somObList.Add(obj_1);
                    }

                    else if ((line.Substring(0, 4) == "1001"))
                    {
                        string[] strArrFields2 = Regex.Split(line, @"(.{6})" + "(.{20})" + "(.{15})").Where(s => !string.IsNullOrEmpty(s)).ToArray();                        
                        someObject obj_1 = new someObject();
                        obj_1.Line2_ID = int.Parse(strArrFields2[0].TrimEnd(' '));
                        obj_1.Line2_Attribute3 = decimal.Parse(strArrFields2[1].TrimEnd(' '));
                        obj_1.Line2_Attribute4 = strArrFields2[2].TrimEnd(' ');
                        somObList.Add(obj_1);
                    }

                    else
                    {
                        string[] strArrFields3 = Regex.Split(line, @"(.{6})" + "(.{7})" + "(.{7})" + "(.{7})").Where(s => !string.IsNullOrEmpty(s)).ToArray();                        
                        someObject obj_1 = new someObject();
                        obj_1.Line3_ID = int.Parse(strArrFields3[0].TrimEnd(' '));
                        obj_1.data_pos1 = decimal.Parse(strArrFields3[1].TrimEnd(' '));
                        obj_1.data_pos2 = decimal.Parse(strArrFields3[2].TrimEnd(' '));
                        obj_1.data_pos3 = decimal.Parse(strArrFields3[3].TrimEnd(' '));                        
                        somObList.Add(obj_1);
                    }  
                } 
            }
            catch (FileNotFoundException ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("Program Exited");
                Environment.Exit(99);
            }             
            foreach (someObject o in somObList)
            {
                Console.WriteLine("{0},{1},{2}\n{3},{4},{5}\n{6},{7},{8},{9}",
                    o.Line1_ID, o.Line1_Attribute1, o.Line1_Attribute2, o.Line2_ID, o.Line2_Attribute3, o.Line2_Attribute4, o.Line3_ID, o.data_pos1, o.data_pos2, o.data_pos3);
            }
            somObList.Clear();
        }
    }
}

2 个答案:

答案 0 :(得分:0)

你在这里。这对于您的任务的具体细节并不准确,但我希望引导您朝着合适的方向前进。我自己仍然是一名新开发人员......但也许你会从这种稍微不同的方法中受益。首先,将对象分成新的类文件。这是我的,名为Item.cs

    public class Item
    {
        public string Attribute1 { get; set; }
        public string Attribute2 { get; set; }
    }

这是程序。就像我说的那样,这对你来说不会即插即用,但如果你注意到我正在努力完成你的任务,你甚至可以进一步完善它。我只是使用一个基本的文本文件进行快速测试..让我知道它是如何为你工作的。

    static void Main(string[] args)
    {
        List<Item> myItems = new List<Item>();

        List<string> myFile = File.ReadAllLines("C:\\Path\\Values.txt").ToList();

        foreach (string value in myFile)
        {
            switch(value.Substring(0,4))
            {
                case "1001":
                    myItems.Add(MyParseMethod1(value));
                    break;
                case "1002":
                    myItems.Add(MyParseMethod2(value));
                    break;
                default:
                    myItems.Add(MyDefaultParser(value));
                    break;
            }
        }
    }

    public static Item MyParseMethod1(string stringIWishtoParse)
    {
        Item myItem = new Item();

        //Parse string, set object values

        //myItem.Attribute1 = whatever portion you want from your string

        return myItem;
    }

    public static Item MyParseMethod2(string stringIWishtoParse)
    {
        Item myItem = new Item();

        //Parse string, set object values

        //myItem.Attribute1 = whatever portion you want from your string

        return myItem;
    }

    public static Item MyDefaultParser(string stringIWishtoParse)
    {
        //Follow pattern from other methods
    }
}

答案 1 :(得分:0)

首先,这是您的数据文件的外观吗?

1000 AttributeOne AttributeTwo
1001 123456.000000 AttributeFour
1002 1234.0 2345.0 3456.0 
1003 1234.0 2345.0 3456.0 
1004 1234.0 2345.0 3456.0 
1000 AttributeOne AttributeTwo  
1001 456789.000000 AttributeFour
1002 1234.0 2345.0 3456.0 
1003 1234.0 2345.0 3456.0 
1004 1234.0 2345.0 3456.0 
1000 AttributeOne AttributeTwo
1001 234567.000000 AttributeFour
1002 1234.0 2345.0 3456.0 
1003 1234.0 2345.0 3456.0 
1004 1234.0 2345.0 3456.0 
1000 AttributeOne AttributeTwo
1001 345678.000000 AttributeFour
1002 1234.0 2345.0 3456.0 
1003 1234.0 2345.0 3456.0 
1004 1234.0 2345.0 3456.0

其次,为什么使用正则表达式来分割文本?如果你担心间隔,为什么不规范它。

接下来,你将在每个if语句中覆盖你的对象。

这是我修改后的代码版本。

using System;
using System.Linq;
using System.Data;
using System.Data.Linq;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

namespace OverwritingClassObjectHelp
{
    public class someObject
    {
        //Line 1
        public int Line1_ID;
        public string Line1_Attribute1;
        public string Line1_Attribute2;

        //Line 2
        public int Line2_ID;
        public decimal Line2_Attribute3;
        public string Line2_Attribute4;

        //Line 3
        public int Line3_ID;
        public decimal data_pos1;
        public decimal data_pos2;
        public decimal data_pos3;  

        //Line 4
        public int Line4_ID;
        public decimal data_pos4;
        public decimal data_pos5;
        public decimal data_pos6; 
    }

    class MainClass
    {
        public static void Main (string[] args)
        {
            string filepathRead = @"C:\Users\C121736\Desktop\SampleFile.txt";
            List<someObject> somObList = new List<someObject>();
            try
            {
                FileStream fs = new FileStream(filepathRead, FileMode.Open, FileAccess.Read);
                StreamReader reader = new StreamReader(fs);
                someObject obj_1 = null;

                while (!reader.EndOfStream) 
                {                         
                    string line = reader.ReadLine();


                    if(String.IsNullOrWhiteSpace(line))
                    {
                        // if line is empty do nothing
                        continue;
                    }
                    else if ((line.Substring(0, 4) == "1000"))
                    {
                        // normalize
                        line = Regex.Replace(line, @"\s+", " ");
                        string[] strArrFields = line.Split();

                        obj_1 = new someObject();                        
                        obj_1.Line1_ID = int.Parse(strArrFields[0]);
                        obj_1.Line1_Attribute1 = strArrFields[1];
                        obj_1.Line1_Attribute2 = strArrFields[2];
                    }

                    else if ((line.Substring(0, 4) == "1001"))
                    {
                        if(obj_1 == null) continue;

                        // normalize
                        line = Regex.Replace(line, @"\s+", " ");
                        string[] strArrFields = line.Split();


                        obj_1.Line2_ID = int.Parse(strArrFields[0]);
                        obj_1.Line2_Attribute3 = decimal.Parse(strArrFields[1]);
                        obj_1.Line2_Attribute4 = strArrFields[2];
                        somObList.Add(obj_1);
                    }

                    else if(line.Substring(0, 4) == "1003") 
                    {
                        if(obj_1 == null) continue;

                        // normalize
                        line = Regex.Replace(line, @"\s+", " ");
                        string[] strArrFields = line.Split();

                        obj_1.Line3_ID = int.Parse(strArrFields[0]);
                        obj_1.data_pos1 = decimal.Parse(strArrFields[1]);
                        obj_1.data_pos2 = decimal.Parse(strArrFields[2]);
                        obj_1.data_pos3 = decimal.Parse(strArrFields[3]);
                    }
                    else if(line.Substring(0, 4) == "1004")
                    {
                        if(obj_1 == null) continue;

                        // normalize
                        line = Regex.Replace(line, @"\s+", " ");
                        string[] strArrFields = line.Split();


                        obj_1.Line4_ID = int.Parse(strArrFields[0]);
                        obj_1.data_pos4 = decimal.Parse(strArrFields[1]);
                        obj_1.data_pos5 = decimal.Parse(strArrFields[2]);
                        obj_1.data_pos6 = decimal.Parse(strArrFields[3]);
                        somObList.Add(obj_1);
                        obj_1 = null;
                    }
                } 
            }
            catch (FileNotFoundException ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("Program Exited");
                Environment.Exit(99);
            }             
            foreach (someObject o in somObList)
            {
                Console.WriteLine("{0},{1},{2}\n{3},{4},{5}\n{6},{7},{8},{9}",
                                  o.Line1_ID, o.Line1_Attribute1, o.Line1_Attribute2, o.Line2_ID, o.Line2_Attribute3, o.Line2_Attribute4, o.Line3_ID, o.data_pos1, o.data_pos2, o.data_pos3);
            }
            somObList.Clear();
        }
    }
}