2017-01-31 14 views
0

Этот код функционирует путем чтения содержимого текстового файла, управления данными в нем и отображения вывода в текстовом поле.Отображение нулевой или нулевой информации из текстового файла в C# ASP.Net

using (StreamReader stRead = new StreamReader(FileUpload1.PostedFile.InputStream)) 
      { 
       string filenameDate = FileUpload1.FileName.Substring(15, 2); 
       Dictionary<string, int> dMyobject = new Dictionary<string, int>(); 

       while (!stRead.EndOfStream) 
       { 
        var readedLine = stRead.ReadLine(); 

        if (!string.IsNullOrWhiteSpace(readedLine)) 
        { 

         //int readedLineTime = Convert.ToInt32(readedLine.Substring(09, 02)); 
         string sDate = readedLine.Substring(0, 11); 

         MatchCollection collection = Regex.Matches(readedLine, @"D;"); 
         countedChars = collection.Count; 




         if (!dMyobject.Keys.Contains(sDate)) 
         { 
          dMyobject.Add(sDate, collection.Count); 
         } 
         else 
         { 
          dMyobject[sDate] = dMyobject[sDate] + collection.Count; 
         } 


        } 
        textfileContent += readedLine + Environment.NewLine; 
        i++; 
       } 
       txtContent.Text = textfileContent; 
       lblLineCount.Text = i.ToString(); 
       //Label1.Text = this.TextBox1.Text.Split(new Char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).Length.ToString(); 
       lblFileDate.Text = filenameDate; 




       foreach (var item in dMyobject) 
       { 
        textfileOutput += (item.Key + " " + item.Value) + Environment.NewLine; 
        // textfileOutput += (item.Value) + Environment.NewLine; 
       } 
       txtOutput.Text = textfileOutput; 



      } 

Каждая строка в текстовом файле содержит дату и серию рисунков. этот код считывает каждую строку, разделенную датами, и подсчитывает общее появление шаблона, в этом примере, считая шаблон «D;» и суммировать его общее количество за дату (строки с той же датой должны быть суммированы). Например

enter image description here

работает код даст этот Токовый выход

2016-12-01 - 7 
2016-12-02 - 9 
2016-12-03 - 5 
2016-12-05 - 1 

Моя цель и желаемый результат должен включать в выходной дату с нулевым значением. В моем примере, не было 2016-12-04 запись ** ожидаемый результат не должен отображаться дата еще и дисплей 0 или пустой, таких как: **

2016-12-01 - 7 
2016-12-02 - 9 
2016-12-03 - 5 
2016-12-04 - 0 
2016-12-05 - 1 

ответ

1

Это сделает это.

using (StreamReader stRead = new StreamReader(@"c:\test.txt")) 
{ 
    string filenameDate = "test"; 
    string textfileContent = string.Empty; 
    int i = 0; 
    string textfileOutput = string.Empty; 
    Dictionary<string, int> dMyobject = new Dictionary<string, int>(); 

    while (!stRead.EndOfStream) 
    { 
     var readedLine = stRead.ReadLine(); 

     if (!string.IsNullOrWhiteSpace(readedLine)) 
     { 
      string sDate = readedLine.Substring(0, 11).Trim(); 

      MatchCollection collection = Regex.Matches(readedLine, @"D;"); 
      if (!dMyobject.Keys.Contains(sDate)) 
      { 
       dMyobject.Add(sDate, collection.Count); 
      } 
      else 
      { 
       dMyobject[sDate] = dMyobject[sDate] + collection.Count; 
      } 


     } 
     textfileContent += readedLine + Environment.NewLine; 
     i++; 
    } 

    var date = DateTime.Parse(dMyobject.First().Key); 
    var beginOfMonth = new DateTime(date.Year, date.Month, 1); 
    var days = new Dictionary<string, int>(); 
    for (var x = 0; x < DateTime.DaysInMonth(date.Year, date.Month); x++) 
    { 
     days.Add(beginOfMonth.AddDays(x).ToString("yyyy-MM-dd"), 0); 
    } 

    foreach (var item in days) 
    { 
     textfileOutput += (dMyobject.ContainsKey(item.Key) ? (item.Key + " " + dMyobject[item.Key]) : (item.Key + " 0")) + Environment.NewLine; 
    } 

} 

Таким образом, последние бит код первым создают диапазоны дат, которые необходимы, выбирая дату от вашего Dictionary и перебора в последний день этого месяца. Затем он проверяет ваши совпадения и числа против диапазонов дат, и если есть совпадение, используйте обновленный счет вместо 0.

+0

Вы правы, извиняйтесь, пожалуйста, см. Мой отредактированный вопрос @johanP – rickyProgrammer

+0

Обновлено мой ответ – JohanP

+0

Спасибо за это, но единственное, чего может не хватить, это то, очень первая дата равна null, например, dec 1 имеет значение null, она не отображает ее – rickyProgrammer

1

В файле загрузки, то есть 2016 год -12-04 line, вы просто отредактируете вас Regex для получения всех символов и подсчета общего балла.

fix 1: Проверьте непрерывное время.

using (StreamReader stRead = new StreamReader(FileUpload1.PostedFile.InputStream)) 
       { 
        string filenameDate = FileUpload1.FileName.Substring(15, 2); 
        SortedDictionary<string, int> dMyobject = new SortedDictionary<string, int>(); //this is a dictionary sorted by key 
      DateTime? startDatetime = null, endDatetime = null;//got mininum and maxinum dates, at late will be check the continuous time 

        while (!stRead.EndOfStream) 
        { 
         var readedLine = stRead.ReadLine(); 

         if (!string.IsNullOrWhiteSpace(readedLine)) 
         { 

          string sDate = readedLine.Substring(0, 11).Trim(); 
        DateTime date; 
        if (DateTime.TryParse(sDate, out date)) 
        { 
         if (startDatetime.HasValue == false) 
          startDatetime = date; 
         endDatetime = date; 
//got start date and end date 
//if date does not from big to small 
//here need compare bwteen date and endDatetime 
        } 


       MatchCollection collection = Regex.Matches(readedLine, "(?<c>[A-Z]+);"); 

          if (!dMyobject.Keys.Contains(sDate)) 
          { 
           dMyobject.Add(sDate, GetTotal(collection)); 
          } 
          else 
          { 
           dMyobject[sDate] = dMyobject[sDate] + GetTotal(collection); 
          } 


         } 
         textfileContent += readedLine + Environment.NewLine; 
         i++; 
        } 

    //here is check the continuous time 
      if (startDatetime.HasValue && endDatetime.HasValue) 
      { 
       for (var dt = startDatetime; dt.Value.CompareTo(endDatetime) <= 0; dt = dt.Value.AddDays(1)) 
       { 
        string key = dt.Value.ToString("yyyy-MM-dd"); 

        if (!dMyobject.Keys.Contains(key)) 
        { 
         dMyobject[key] = 0; 
        } 
       } 
      } 


        txtContent.Text = textfileContent; 
        lblLineCount.Text = i.ToString(); 
        //Label1.Text = this.TextBox1.Text.Split(new Char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).Length.ToString(); 
        lblFileDate.Text = filenameDate; 




        foreach (var item in dMyobject) 
        { 
         textfileOutput += (item.Key + " " + item.Value) + Environment.NewLine; 
         // textfileOutput += (item.Value) + Environment.NewLine; 
        } 
        txtOutput.Text = textfileOutput; 



       } 


    //this method is a new method, it got total score, and if you rule chanage you can set `D` +1, `A` +2 etc. 
      private int GetTotal(MatchCollection collection) 
      { 
       Dictionary<string, int> point = new Dictionary<string, int>(); 
       point["D"] = 1; 
       point["A"] = 0; 

       int total = 0; 
       foreach (Match m in collection) 
       { 
        string str = m.Groups["c"].Value; 
        if (point.ContainsKey(str)) 
         total += point[str]; 
       } 
       return total; 
      } 
+0

Это не получить желаемый результат, поскольку он суммирует все общее «D» и «A„возникновение, как то, что вопрос гласит, что следует рассчитывать на“D; «появление PER DATE, пожалуйста, см. желаемый результат, спасибо – rickyProgrammer

+0

Я был исправлен. Используйте мой код, который вы можете определить для каждой буквы, например: если каждый' D' добавляет 1 балл, каждый 'A' добавляет 2 точки и каждый' O' вычитайте 1 балл, затем используйте мой код, чтобы удовлетворить это легко. –

0

Добавление комментариев JohanP ответа, код работает нормально ожидать, дата подстрока неправильно в исходном коде, и нет никакой проблемы с Словаре 0 Значение

+0

Там недостает, вот когда первая дата равна нулю. – rickyProgrammer

0

ответ JohanP является большой помощью, но есть ограничения, так как и необходимо записать первые даты, когда он равен нулю. Поэтому, основываясь на его ответе, я придумал эти коды.

using (StreamReader stRead = new StreamReader(FileUpload1.PostedFile.InputStream)) 
     { 

      Dictionary<string, int> dMyobject = new Dictionary<string, int>(); 

      while (!stRead.EndOfStream) 
      { 
       var readedLine = stRead.ReadLine(); 
       if (!string.IsNullOrWhiteSpace(readedLine)) 
       { 
        //int readedLineTime = Convert.ToInt32(readedLine.Substring(11, 02)); 
        string sDate = readedLine.Substring(11, 2); 

        MatchCollection collection = Regex.Matches(readedLine, @"D;"); 
        countedChars = collection.Count; 


        if (!dMyobject.Keys.Contains(sDate)) 
        { 
         dMyobject.Add(sDate, collection.Count); 
        } 
        else 
        { 
         dMyobject[sDate] = dMyobject[sDate] + collection.Count; 
        } 
       } 
       textfileContent += readedLine + Environment.NewLine; 
       i++; 
      } 
      txtContent.Text = textfileContent; 
      lblLineCount.Text = i.ToString(); 



      var prevDate = string.Empty; 
      int tester = 01; 

      foreach (var item in dMyobject) 
      { 
       int testCorrectStart = Convert.ToInt32(item.Key) - tester; 
       if (testCorrectStart == 0) 
       { 
        if (!string.IsNullOrEmpty(prevDate)) 
        { 
         var cur = Int32.Parse(item.Key); // convert current key into int 
         var prev = Int32.Parse(prevDate); 
         int dayDiff = cur - prev; 
         for (var x = 0; x < dayDiff - 1; x++) // run through day difference, add it to the last date that was added 
         { 

          textfileOutput += ((prev + (x + 1)).ToString() + " 0" + Environment.NewLine); 

         } 
        } 

        textfileOutput += (item.Key + " " + item.Value) + Environment.NewLine; 
        prevDate = item.Key; 
        tester++; 
       } 

       else 
       { 

        if (!string.IsNullOrEmpty(tester.ToString())) 
        { 
         var cur = Int32.Parse(item.Key); // convert current key into int 
         var prev = Int32.Parse(tester.ToString()); 
         int dayDiff = cur - prev; 
         for (var x = 0; x < dayDiff ; x++) // run through day difference, add it to the last date that was added 
         { 

          textfileOutput += ("0" +(prev + x).ToString() + " 0" + Environment.NewLine); 
         } 
        } 
        textfileOutput += (item.Key + " " + item.Value) + Environment.NewLine; 
        prevDate = item.Key; 
        tester = Convert.ToInt32(prevDate) + 1; 
       } 
      } 
      txtOutput.Text = textfileOutput; 
     } 

вы можете проверить его correcteness