2017-01-30 8 views
0

Это образец текстового файлаCount Pattern/String Вхождение в каждой группе с помощью C# в ASP.Net

enter image description here

линии классифицируется по дате, в каждую строку дату можно повторить, как, например, 1 декабря и 2 имеют две записи. Ожидаемый результат следует считать шаблон «D;» например, на сегодняшний день

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

Это то, что я в настоящее время

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

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

       if (!string.IsNullOrWhiteSpace(readedLine)) 
       { 

        for (int j = 01; j <= 31; j++) 
        { 
         int readedLineTime = Convert.ToInt32(readedLine.Substring(09, 02)); 
         if (readedLineTime == j) 
         { 

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

          textfileOutput += readedLine.Substring(0, 11) + " - " + countedChars + Environment.NewLine; 

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

      TextBox1.Text = textfileOutput; 
      TextBox2.Text = textfileContent; 
      Label1.Text = i.ToString(); 
      //Label1.Text = this.TextBox1.Text.Split(new Char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).Length.ToString(); 
      // Label2.Text = filename; 

     } 

и это его выходной ток, который отображается в многокорпусных линии текстовое поле

2016-12-01 - 4 
2016-12-01 - 3 
2016-12-02 - 4 
2016-12-02 - 5 
2016-12-03 - 5 
+0

Рики, так что вы хотите дату и количество вхождений «D» против него. Это правильное понимание? – A3006

+0

Я хочу посчитать появление «D;» в каждой строке по дате и подсчитывать или комбинировать счетчик с той же датой, как и с примером – rickyProgrammer

+0

Хорошо. И что для (int j = 01; j <= 31; j ++) для? Кроме того, ваш входной файл «csv»? – A3006

ответ

1

Позвольте мне знать, если это сработает.

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++; 
      } 

Вам нужно будет нажать эти значения в какой-либо коллекции. Чтобы вы могли это проверить.

Позже, для использования этих значений для печати или что-либо, использование следующих

foreach (var item in dMyobject) 
      { 
       Console.WriteLine(item.Key + " " + item.Value); 
      } 
+0

Сказав это, я должен признать, что это не хороший код. Как я уже говорил, если ваш тип входного файла - csv, вы можете оптимизировать код. Я дал этот ответ, поскольку не знал тип ввода. :-) – A3006

+0

inout type - просто текстовый файл – rickyProgrammer

+0

Итак, что выше работает для вас? – A3006

0
string line = ""; 
     Dictionary<string, int> list = new Dictionary<string, int>(); 
     int count; 
     if (File.Exists(fileName) == true) 
     { 
      StreamReader objReader; 
      objReader = new StreamReader(fileName); 
      StreamWriter file = new StreamWriter(OutputfileName"); 
      do 
      { 
       line = objReader.ReadLine(); 
       string temp = line.Substring(0, 10); 
       if (!list.ContainsKey(temp)) 
       { 
        MatchCollection collection = Regex.Matches(line, @"D;"); 
        count = collection.Count; 
        list.Add(temp, count); 
       } 
       else 
       { 
        MatchCollection collection = Regex.Matches(line, @"D;"); 
        count = collection.Count; 
        var val = list[temp]; 
        list[temp] = count + val; 
       } 
      } while (objReader.Peek() != -1); 
      foreach (var j in list) 
      { 
       file.WriteLine(j.Key + " - " + j.Value+"\n"); 
      } 
      file.Close(); 
     }