【问题标题】:Adjust name of file being read at end of loop without breaking loop在循环结束时调整正在读取的文件的名称而不中断循环
【发布时间】:2012-12-04 09:48:46
【问题描述】:

每天结束时会生成 2 份报告。我希望能够在每个月底对它们进行分析。

在每个文件中都有一千行左右的长 ASCII 字符串。这已成功编码,但一次只能提取和执行一个文件的分析。

我将尝试在下面输入代码的相关结构。我希望这足以让您了解需要做什么。如果没有,我很乐意发布整个内容。

using (StreamReader reader = new StreamReader("YYYYMMDD----1234D.dat"))
{
while loop //this goes through all the lines in the file. 
{if //if meets certain criteria then store into a list, otherwise ignore

}
foreach // this part does the analysis of all the values in the list, totals, etc

。

第一个报告是上述格式,另一个用不同的数字代替 1234D(为了参数,5678D,所以:yyyymmdd----5678D)。这两个数字始终保持不变。

我希望能够将每个文件中的所有数据存储到我的列表中,然后对整个月进行分析,而不是每天进行细分,因此它会循环遍历每个文件,当它到达文件的末尾,将名称增加一天,循环遍历该名称等(或查找所有带有 X 月的文件 - 以更好的为准)。这将填充列表,然后 foreach 将执行其分析和输出。预计我会将所有需要的文件放入与程序当前使用的文件夹相同的文件夹中。

当前代码:

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

class Program 
{
    public class EntryLine
    {
        public int I { get; set; }
        public string LineStart { get; set; }
        public string Letters { get; set; }
        public int TVolume { get; set; }
        public long TPrice { get; set; }
        public double MVolume { get; set; }
        public string Currency { get; set; }
        public string DateTime {get; set; }

    }

    static void Main(string[] args)
    {
        List<EntryLine> myList = new List<EntryLine>();
        int i = 1;
        using (StreamReader reader = new StreamReader("20121203----1234D.dat"))
        {
            string line;
            var locations = new Dictionary<string, int[]>() {
            {"210", new [] {405, 4, 128, 12, 141, 12, 247, 15, 121, 3}}, 
            {"310", new [] {321, 4, 112, 12, 125, 12, 230, 15, 105, 3}}, 
            {"410", new [] {477, 4, 112, 12, 125, 12, 360, 15, 105, 3}} 
        };

            while ((line = reader.ReadLine()) != null)
            {
                var lineStart = line.Substring(0, 3);

                if (lineStart == "210" || lineStart == "310" || lineStart == "410")
                {
                    var currentLocations = locations[lineStart];
                    var letters = line.Substring(currentLocations[0], currentLocations[1]);

                    var tvolume =
                        int.Parse(line.Substring(currentLocations[2], currentLocations[3])) +
                        int.Parse(line.Substring(currentLocations[4], currentLocations[5]));

                    var tprice = long.Parse(line.Substring(currentLocations[6], currentLocations[7]));
                    var mvolume = tprice * tvolume * 0.01 * 0.0000001;
                    var currency = line.Substring(currentLocations[8], currentLocations[9]);

                    myList.Add(new EntryLine()
                    {
                        I = i,
                        LineStart = lineStart,
                        Letters = letters,
                        TVolume = tvolume,
                        TPrice = tprice,
                        MVolume = mvolume,
                        Currency = currency
                    });
                    i = i + 1;
                }
            }

            var x = myList.GroupBy(g => new { g.Letters, g.Currency })
                .Select(a => new { a.Key.Letters, a.Key.Currency, TSum = a.Sum(s => s.TVolume), MSum = a.Sum(s => s.MVolume) });

            foreach (var item in x)
            {
                Console.WriteLine("{0} currency: {1} tvolume: {2} mVolume: {3}", item.Letters, item.Currency, item.TSum, item.MSum);
            }
        } Console.ReadLine();
    }

}

【问题讨论】:

    标签: c# date increment


    【解决方案1】:

    有很多方法可以做到这一点。这是一个选择:首先,将过程分解为几个函数,以便于代码维护。然后使用一个函数遍历所有文件并构建信息列表,然后使用另一个函数分析该信息。

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;
    
    namespace ReportAnalysis {
    static class Program {
        static void Main() {
            //lets run the analysis for Nov, 2012
    
            //First, read in all report files, and store relevant lines
            var reportInfo = ReportAnalyzer.ReadFiles(2012, 11);
    
            //Now analyze all files at once
            ReportAnalyzer.RunAnalysis(reportInfo);
        }
    }
    class ReportAnalyzer {
        struct ReportFile {
            public string Path;
            public DateTime Date;
            public List<string> Lines;
        }
    
        public static IList<ReportFile> ReadFiles(int year, int month) {
            //Put names of files here.
            string[] fileNames = new string[] { "{0:YYYYMMDD}----1234D.dat", "{0:YYYYMMDD}----5678D.dat" };
    
            DateTime dateStart = new DateTime(year, month, 1); //start of month
            DateTime dateEnd = dateStart.AddMonths(1); //start of NEXT month (i.e. 1 day past end of this month)
    
            var reportList = new List<ReportFile>();
    
            DateTime date = dateStart;
            while (date < dateEnd) {  //we don't actually get to dateEnd, just the day before it.
                foreach (var fileTemplate in fileNames) {
                    //insert the date in YYYYMMDD format
                    var file = string.Format(fileTemplate, date);
                    if (File.Exists(file)) {
                        var report = new ReportFile() {
                            Date = date,
                            Path = file,
                            Lines = GetReportLines(file)
                        };
                        reportList.Add(report);
                    }
                }
                //now jump to next day
                date = date.AddDays(1);
            }
            return reportList;
        }
    
        private static List<string> GetReportLines(string file) {
            var lines = new List<string>();
            try {
                using (StreamReader reader = new StreamReader(file)) {
                    while (!reader.EndOfStream) {
                        var line = reader.ReadLine();
                        if (true /* insert criteria */)
                            lines.Add(line);
                    }
                }
            } catch (Exception ex) {
                //log the error however you see fit
                lines.Add(string.Format("ERROR Could not open report file {0}: {1}", file, ex.Message));
            }
            return lines;
        }
    
        public static void RunAnalysis(IList<ReportFile> reports) {
            foreach (var r in reports) {
                //Do whatever analysis you need
                Console.WriteLine(r.Date);
                Console.WriteLine(r.Path);
                foreach (var line in r.Lines)
                    Console.WriteLine(line);
            }
        }
    }
    }
    

    这是一个“简短而甜蜜”的版本,只介绍了重要的部分:

    void ProcessReports {
        string[] fileNames = new string[] { "{0:YYYYMMDD}----1234D.dat", "{0:YYYYMMDD}----5678D.dat" };
        DateTime dateStart = new DateTime(year, month, 1); //start of month
        DateTime dateEnd = dateStart.AddMonths(1); //start of NEXT month (i.e. 1 day past end of this month)
        List<string> lines = new List<string>();
        DateTime date = dateStart;
        while (date < dateEnd) {  //we don't actually get to dateEnd, just the day before it.
            foreach (var fileTemplate in fileNames) {
                //insert the date in YYYYMMDD format
                var file = string.Format(fileTemplate, date);
                if (File.Exists(file)) {
                    using (StreamReader reader = new StreamReader(file)) {
                        while (!reader.EndOfStream) {
                            var line = reader.ReadLine();
                            if (true /* insert criteria */)
                                lines.Add(line);
                        }
                    }
                }
            }
            //now jump to next day
            date = date.AddDays(1);
        }   
        //Now we have all the lines. Let's process them;
        foreach (var line in lines) {
            //do something with the report lines
        }
    }
    

    【讨论】:

    • @Cylen:看一下我获得该月连续每一天的 YYYYMMDD 格式日期的方式。基本上,您只需使用 DateTime 对象。在每个文件之后,您可以通过调用AddDays(1) 来增加日期。然后您可以通过简单地执行 date.ToString("YYYYMMDD") 或类似地 string.Format("{0:YYYYMMDD}", date); 以“YYYMMDD”格式获取日期
    • holy schmoly 我认为这是一个 2 行的事情。唉,不,但这读起来很好,对我来说很有意义,更重要的是不需要 linq(我被告知现在要避免的事情)。所以如果我把它放在我当前的代码上方,这将取代我当前的流阅读器行?
    • 代码的格式化方式,你必须剪掉一些“样板”代码才能将它插入到你的项目中。一方面,您的代码已经是某个命名空间的一部分,因此只需将上面命名空间大括号内的代码复制并粘贴到您当前的命名空间中。
    • 而且您实际上并不需要复制所有内容。只需尝试通读并了解每个部分在做什么。如有任何不明白的地方,请随时提出更多问题。最后,您可能只想复制几行即可获得所需的内容。我提供的完整示例是为了演示如何将逻辑分成多个方法,以便更容易理解和维护每个部分。
    • 我添加了一个包含在单个方法中的缩短版本,只是为了让您更容易看到重要部分,例如更改文件名中的日期。
    【解决方案2】:

    如果您只是将您的 foreach 移出您的 using 块,那么没有什么能阻止您使用您的第二个文件名复制 using 块,或者将 using 块放入您传递的自己的循环中文件名:

    string[] filenames = new string[] {
        "20121203 ----1234D.dat",
        "20121204 ----1234D.dat",
        "20121205 ----1234D.dat" };
    List<Whatever> yourListOfMatchingItems = new List<Whatever>();
    
    foreach (string filename in filenames)
    {
        using (StreamReader reader = new StreamReader(filename))
        {
            while (/* whatever you had before */)
            {
                if (/* whatever you had before */)
                {
                }
            }
        }
    }
    foreach (/* item in your list */)
    {
    }
    

    【讨论】:

    • 您好 Rawling,我从您的回复中了解到如何让同一程序读取其他文件,但我不清楚如何将 20121203 ----1234D.dat 更改为例如 20121204----1234D.dat(昨天和今天),无需停止程序并手动执行。
    • @Cylen 我已经把我的最后一个例子变成了更具体的东西。
    【解决方案3】:

    您需要动态创建文件名,而不是对其进行硬编码。然后,您可以遍历所有文件以生成值列表,然后处理它们。

    为什么不把它分成几个方法呢?比如:

    public void Process()
    {
        // logic to get string[] of filenames here. You could loop through each
        // day you need a list for and generate a filename for the given day
        var values = new List<T>();
        foreach (var filename in filenames)
        {
            var valuesFromFile = GetValuesFrom(filename);
            values.AddRange(valuesFromFile);
        }
        ProcessValues(values);
    }
    
    private List<T> GetValuesFrom(string filename)
    {
        var values = new List<T>();
        while loop //this goes through all the lines in the file. 
        {if //if meets certain criteria then store into a list, otherwise ignore
        }
        return values;
    }
    
    private void ProcessValues(List<T> values)
    {
        foreach // this part does the analysis of all the values in the list, totals, etc
    }
    

    T当然是你的值的类型

    【讨论】:

      猜你喜欢
      • 2017-03-08
      • 1970-01-01
      • 1970-01-01
      • 2013-09-16
      • 1970-01-01
      • 1970-01-01
      • 2019-11-10
      相关资源
      最近更新 更多