Advertisement
Guest User

vbbebess

a guest
Jun 3rd, 2017
363
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 6.11 KB | None | 0 0
  1.         Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
  2.         Dim currentRow As String()
  3.         ' Ключі це brand + article, дані це список цін
  4.         Dim data As Dictionary(Of String, List(Of Double)) = New Dictionary(Of String, List(Of Double))
  5.         'Dim prices As Dictionary(Of Integer, Double) = New Dictionary(Of Integer, Double)
  6.  
  7.         Dim brand As String = ""
  8.         Dim article As String = ""
  9.  
  10.         Using csvReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(inputFile.Text, System.Text.Encoding.GetEncoding(1251))
  11.             csvReader.TextFieldType = FileIO.FieldType.Delimited
  12.             csvReader.SetDelimiters(";")
  13.             csvReader.TrimWhiteSpace = True
  14.  
  15.             Console.WriteLine("Time is {0}", System.DateTime.Now.ToString("HH:mm:ss"))
  16.             Console.WriteLine("Создание ключей.")
  17.             While Not csvReader.EndOfData
  18.                 Try
  19.                     currentRow = csvReader.ReadFields()
  20.                     ' Виробник
  21.                     brand = currentRow(2)
  22.                     ' Артикул
  23.                     article = currentRow(1)
  24.  
  25.                     ' Чомусь дані починаються тільки з 3 рядка. Рядок №2 це заголовок
  26.                     If csvReader.LineNumber < 3 Then
  27.                         Continue While
  28.                     End If
  29.  
  30.                     'prices.Add(csvReader.LineNumber, currentRow(7))
  31.                     Dim hashID As String = ""
  32.                     hashID = brand & article
  33.  
  34.                     Dim hash_row_numbers As New List(Of Double)
  35.                     ' currentRow(7) - ціна
  36.                     ' Якщо ключ вже є в словнику, то зробити припущення що даний елемен словника вже містить список цін і просто доадти до цього списку нову ціну
  37.                     If data.ContainsKey(hashID) Then
  38.                         data.Item(hashID).Add(currentRow(7))
  39.                     Else
  40.                         ' інакше створити новий список, додати до нього ціну, створити новий ключ в словнику
  41.                         data.Add(hashID, New List(Of Double))
  42.                         data.Item(hashID).Add(currentRow(7))
  43.                     End If
  44.                 Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
  45.                     MsgBox("Line " & ex.Message & " is invalid.  Skipping")
  46.                 End Try
  47.  
  48.             End While
  49.            
  50.         End Using
  51.         ' Вдруге відкрити файл з даними для порівння з раніше зібраними даними
  52.         Using csvReader2 As New Microsoft.VisualBasic.FileIO.TextFieldParser(inputFile.Text, System.Text.Encoding.GetEncoding(1251))
  53.             csvReader2.TextFieldType = FileIO.FieldType.Delimited
  54.             csvReader2.SetDelimiters(";")
  55.             csvReader2.TrimWhiteSpace = True
  56.  
  57.             Dim best_prices As Dictionary(Of String, Double) = New Dictionary(Of String, Double)
  58.             For Each kk As KeyValuePair(Of String, List(Of Double)) In data
  59.                 Dim bestPrice As Double = 0
  60.                 ' тільки якщо в списку більше одного елементу
  61.                 If kk.Value.Count() > 1 Then
  62.                     bestPrice = kk.Value.Min()
  63.                     best_prices.Item(kk.Key) = bestPrice
  64.                 End If
  65.             Next
  66.             Console.WriteLine("Количество дубликатов: {0}", best_prices.Count())
  67.             Console.WriteLine("Хеширование закончено.")
  68.             If best_prices.Count() < 1 Then
  69.                 MsgBox("Дубликатов не обнаружено")
  70.             End If
  71.             If best_prices.Count() > 1 Then
  72.                 Console.WriteLine("Начато повторное чтение CSV файла и копирование данных {0}", System.DateTime.Now.ToString("HH:mm:ss"))
  73.                 Dim outputCSVFileName As String = outputSaveDir.Text & "\" & otputFileName.Text & ".csv"
  74.                 Dim outputCSVFile As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(outputCSVFileName, False, System.Text.Encoding.GetEncoding(1251))
  75.                 While Not csvReader2.EndOfData
  76.                     Try
  77.                         currentRow = csvReader2.ReadFields()
  78.                         ' Обєднати "комірки" для подальшого запису в файл
  79.                         Dim currentString As String = String.Join(";", currentRow)
  80.                         Dim id As String = currentRow(2) & currentRow(1)
  81.                         ' Якщо ідентифікатор (brand + article) поточного рядка міститься в списку з мінімальними цінами
  82.                         If best_prices.ContainsKey(id) Then
  83.                             ' і якщо ціна в поточному рядку не дорівню мінімальній ціні, пропустити (не записувати в вихідний файл) його
  84.                             If best_prices.Item(id) <> currentRow(7) Then
  85.                                 Console.WriteLine("ID: {0}, цена {1}. №{2}, article: {3}", id, currentRow(7), csvReader2.LineNumber, currentRow(1))
  86.                                 Console.WriteLine("Best price: {0}", best_prices.Item(id))
  87.                                 Continue While
  88.                             End If
  89.                         End If
  90.                         outputCSVFile.WriteLine(currentString)
  91.                     Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
  92.                         MsgBox("Line " & ex.Message & " is invalid.  Skipping")
  93.                     End Try
  94.                 End While
  95.                 outputCSVFile.Close()
  96.             End If
  97.             Console.WriteLine("Конец.")
  98.         End Using
  99.  
  100.     End Sub
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement