There is a file with 1000 lines, a comma separator in the line, the numbers in the second position are: 01.02.03.03.04.05.06. It is necessary to calculate how much was 01,02,03,04,05,06?

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Text.RegularExpressions; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { //Создание папки и подпапок DirectoryInfo papka = new DirectoryInfo(@"C:\Users\a.filatov\Desktop\Test\"); try { papka.CreateSubdirectory(@"Writer"); papka.CreateSubdirectory(@"Incorrect"); } catch (IOException e) { Console.WriteLine(e.Message); } //Путь к файлу string path = @"C:\Users\a.filatov\Desktop\1\COMMA.txt"; //Читаем текст в файле построчно string[] readText = File.ReadAllLines(path); //Объявляем интервал времени TimeSpan intervaltimesum = new TimeSpan(); //Текущее время в элементе массива TimeSpan current_time; //Счётчик int countTime = 0; //Создание потока для записи в файл StreamWriter W = new StreamWriter(@"C:\Users\a.filatov\Desktop\Test\Writer\Write.txt"); StreamWriter A = new StreamWriter(@"C:\Users\a.filatov\Desktop\Test\Incorrect\Incorrect.txt"); //Цикл для считывания строк for (int i = 19; i < 1019; i++) { //Установка разделителем массива запятой string[] elements = readText[i].Split(','); //Если четветрый элемент в строке существует, то работаем с ним if (elements.GetLength(0) > 4) { //Разбор 4 элемента массива try { //Разделитель ":" string[] times = elements[4].Split(':'); int hours = int.Parse(times[0]); int minutes = int.Parse(times[1]); int seconds = int.Parse(times[2]); current_time = TimeSpan.FromHours(hours) + TimeSpan.FromMinutes(minutes) + TimeSpan.FromSeconds(seconds); // Запись в файл W.WriteLine("{0} {1} {2} \t\t Текущее время = {3} Общее время = {4}", i - 18, elements[0], elements[4], current_time, intervaltimesum); //Вывод 4 элемента массива в файл if (current_time.TotalHours > 2) { // в отдельный файл выведем значение более 2-х часов A.WriteLine("{0}", current_time); } else { // если меньше двух часов - тогда суммируем intervaltimesum += current_time; countTime++; } } catch (Exception) { throw; } } } //Закрытие потока A.Close(); //Вывод среднего времени в нужном формате TimeSpan intervalAverage = TimeSpan.FromSeconds(intervaltimesum.TotalSeconds / countTime); Console.WriteLine("Среднее время = {0:hh\\:mm\\:ss}", intervalAverage); //Запись в файл времени W.WriteLine("\n\n Всё время отклонения = {0} в секундах = {1}", intervaltimesum, intervaltimesum.TotalSeconds); //Запись среднего времени W.WriteLine(" Среднее время {0:hh\\:mm\\:ss}", intervalAverage); W.Close(); } } } 

Closed due to the fact that off-topic participants DreamChild , Aries , Dmitriy Simushev , Saidolim , Dmitry D. Oct 5 '15 at 12:30 .

  • Most likely, this question does not correspond to the subject of Stack Overflow in Russian, according to the rules described in the certificate .
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • Understood nothing. What is the second position and what should be counted? And how are these positions divided? - Qwertiy
  • 2
    StackOverflow is a community where programmers help each other, and not just solve other people's tasks for nothing. If you want help, then bother to explain what you have done and what the problems have been. - Alex Krass
  • five
    I vote for the closure of this issue as not relevant topic, because the work for the author - DreamChild
  • I have already done Split with a comma, read 1000 lines of text in a text file line by line, wrote them into an array, a task in another, only 9 positions in a line, 2 line positions contain either 01, or 02, or 03, or 04, or 05, or 06 , it is necessary to calculate how much was: 01,02,03,04,05,06? New to C # don't understand what to apply? - Alex
  • one
    @Alex not, just help solve problems without a code they are burned here very quickly :) - PashaPash

3 answers 3

There are different ways to do this, depending on your knowledge and skills.

For example, here are three options.

  1. Create an intermediate array and comparing the resulting value of the string, sum the corresponding cell.

     String[] readText = File.ReadAllLines("data.txt"); Int32[] arrCounter = { 0, 0, 0, 0, 0, 0 }; foreach (String text in readText) { switch (text.Split(',')[1]) { case "01": arrCounter[0]++; break; case "02": arrCounter[1]++; break; case "03": arrCounter[2]++; break; case "04": arrCounter[3]++; break; case "05": arrCounter[4]++; break; case "06": arrCounter[5]++; break; } } Console.WriteLine(String.Format("01: {0}; 02: {1}; 03: {2}; 04: {3}; 05: {4}; 06: {5}", arrCounter[0], arrCounter[1], arrCounter[2], arrCounter[3], arrCounter[4], arrCounter[5])); 

The disadvantage of this approach is that if there are many values, your code will swell very quickly and will be difficult to maintain. Also, it will not be able to help you if you do not know in advance what the values ​​in the file may be.

  1. Use a special dynamic collection and populate it, in this case a Dictionary.

     Dictionary<String, Int32> dict = new Dictionary<string, int>(); (String text in readText) { String val = text.Split(',')[1]; if (dict.ContainsKey(val)) dict[val]++; else dict.Add(val, 1); } foreach (String key in dict.Keys) Console.WriteLine(String.Format("{0} : {1}", key, dict[key])); 
  2. Use Linq, as in the Bald56rus example, which significantly reduces the code.

     var pre = readText.Select(p => new { Value = p.Split(',')[1] }) .GroupBy(p => p.Value) .Select(p => new { Key = p.Key, Count = p.Count() }); foreach (var p in pre) Console.WriteLine(String.Format("{0} : {1}", p.Key, p.Count)); 
  • The third way gave an error - Alex
  • I didn’t have to use one ( - Alex
  • Please describe the third method in more detail - Alex
  • @Alex, as I said, the chosen method depends on your knowledge. The third way is a separate technology with C # which is called Linq (integrated query language) and occupies a separate chapter for a couple of dozen pages in books. With all the desire, I will not be able to fit all this volume within the scope of the answer) Keep on learning and someday you will come to this and read it yourself, but for now use another way - Alex Krass
  • Tell us then about the first meteor - Alex
 Dictionary<string, int> result = new Dictionary<string,int>(); //Считываем файл в массив строк // если обрабатыватывать надо не все, то можеть считать файл сами var lines = File.ReadAllLines("PathToFiles"); // данная строка означает следующее: // каждую строку разбиваем на массив подстрок, разделитель запятая, // берем 2 элемент массива(отсчет ведется с 0), делаем группировку // по полученному значение и заносим это в новый анонимный тип var pre = lines .Select(x => new { Value = x.Split(new char[] { ',' })[1] }) .GroupBy(x => x.Value); //здесь в результирующий словарь заносим необходимую информацию в следующем формате: Ключ 01, Количество 5, и т.п. foreach (var p in pre) { result.Add(p.Key, p.Count()); } 

PS Code is not tested.

     using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Text.RegularExpressions; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { //Создание папки и подпапок DirectoryInfo papka = new DirectoryInfo(@"C:\Users\a.filatov\Desktop\Test\"); try { papka.CreateSubdirectory(@"Writer"); papka.CreateSubdirectory(@"Incorrect"); } catch (IOException e) { Console.WriteLine(e.Message); } //Путь к файлу string path = @"C:\Users\a.filatov\Desktop\1\COMMA.txt"; //Читаем текст в файле построчно string[] readText = File.ReadAllLines(path); //Объявляем интервал времени TimeSpan intervaltimesum = new TimeSpan(); //Текущее время в элементе массива TimeSpan current_time; //Счётчик int countTime = 0; //Создание потока для записи в файл StreamWriter W = new StreamWriter(@"C:\Users\a.filatov\Desktop\Test\Writer\Write.txt"); StreamWriter A = new StreamWriter(@"C:\Users\a.filatov\Desktop\Test\Incorrect\Incorrect.txt"); Int32[] arrCounter = { 0, 0, 0, 0, 0, 0 }; //Цикл для считывания строк for (int i = 19; i < 1019; i++) { //Установка разделителем массива запятой string[] elements = readText[i].Split(','); switch (elements[1]) { case "01": arrCounter[0]++; break; case "02": arrCounter[1]++; break; case "03": arrCounter[2]++; break; case "04": arrCounter[3]++; break; case "05": arrCounter[4]++; break; case "06": arrCounter[5]++; break; } //Если четветрый элемент в строке существует, то работаем с ним if (elements.GetLength(0) > 4) { //Разбор 4 элемента массива try { //Разделитель ":" string[] times = elements[4].Split(':'); int hours = int.Parse(times[0]); int minutes = int.Parse(times[1]); int seconds = int.Parse(times[2]); current_time = TimeSpan.FromHours(hours) + TimeSpan.FromMinutes(minutes) + TimeSpan.FromSeconds(seconds); // Запись в файл W.WriteLine("{0} {1} {2} \t\t Текущее время = {3} Общее время = {4}", i - 18, elements[0], elements[4], current_time, intervaltimesum); //Вывод 4 элемента массива в файл более 2 часов if (current_time.TotalHours > 2) { // в отдельный файл выведем значение более 2-х часов A.WriteLine("{0}", current_time); } else { // если меньше двух часов - тогда суммируем intervaltimesum += current_time; countTime++; } } catch (Exception) { throw; } } } Console.WriteLine(String.Format("01: {0}; 02: {1}; 03: {2}; 04: {3}; 05: {4}; 06: {5}", arrCounter[0], arrCounter[1], arrCounter[2], arrCounter[3], arrCounter[4], arrCounter[5])); //Закрытие потока A.Close(); //Вывод среднего времени в нужном формате TimeSpan intervalAverage = TimeSpan.FromSeconds(intervaltimesum.TotalSeconds / countTime); Console.WriteLine("Среднее время = {0:hh\\:mm\\:ss}", intervalAverage); //Запись в файл времени W.WriteLine("\n\n Всё время отклонения = {0} в секундах = {1}", intervaltimesum, intervaltimesum.TotalSeconds); //Запись среднего времени W.WriteLine(" Среднее время {0:hh\\:mm\\:ss}", intervalAverage); W.Close(); } } } 
    • Corrected under your requirements. - Alex Krass
    • Thank you earned ...... - Alex
    • Thank you very much !!!!!!!!!!!!!! - Alex