Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
- Dim currentRow As String()
- ' Ключі це brand + article, дані це список цін
- Dim data As Dictionary(Of String, List(Of Double)) = New Dictionary(Of String, List(Of Double))
- 'Dim prices As Dictionary(Of Integer, Double) = New Dictionary(Of Integer, Double)
- Dim brand As String = ""
- Dim article As String = ""
- Using csvReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(inputFile.Text, System.Text.Encoding.GetEncoding(1251))
- csvReader.TextFieldType = FileIO.FieldType.Delimited
- csvReader.SetDelimiters(";")
- csvReader.TrimWhiteSpace = True
- Console.WriteLine("Time is {0}", System.DateTime.Now.ToString("HH:mm:ss"))
- Console.WriteLine("Создание ключей.")
- While Not csvReader.EndOfData
- Try
- currentRow = csvReader.ReadFields()
- ' Виробник
- brand = currentRow(2)
- ' Артикул
- article = currentRow(1)
- ' Чомусь дані починаються тільки з 3 рядка. Рядок №2 це заголовок
- If csvReader.LineNumber < 3 Then
- Continue While
- End If
- 'prices.Add(csvReader.LineNumber, currentRow(7))
- Dim hashID As String = ""
- hashID = brand & article
- Dim hash_row_numbers As New List(Of Double)
- ' currentRow(7) - ціна
- ' Якщо ключ вже є в словнику, то зробити припущення що даний елемен словника вже містить список цін і просто доадти до цього списку нову ціну
- If data.ContainsKey(hashID) Then
- data.Item(hashID).Add(currentRow(7))
- Else
- ' інакше створити новий список, додати до нього ціну, створити новий ключ в словнику
- data.Add(hashID, New List(Of Double))
- data.Item(hashID).Add(currentRow(7))
- End If
- Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
- MsgBox("Line " & ex.Message & " is invalid. Skipping")
- End Try
- End While
- End Using
- ' Вдруге відкрити файл з даними для порівння з раніше зібраними даними
- Using csvReader2 As New Microsoft.VisualBasic.FileIO.TextFieldParser(inputFile.Text, System.Text.Encoding.GetEncoding(1251))
- csvReader2.TextFieldType = FileIO.FieldType.Delimited
- csvReader2.SetDelimiters(";")
- csvReader2.TrimWhiteSpace = True
- Dim best_prices As Dictionary(Of String, Double) = New Dictionary(Of String, Double)
- For Each kk As KeyValuePair(Of String, List(Of Double)) In data
- Dim bestPrice As Double = 0
- ' тільки якщо в списку більше одного елементу
- If kk.Value.Count() > 1 Then
- bestPrice = kk.Value.Min()
- best_prices.Item(kk.Key) = bestPrice
- End If
- Next
- Console.WriteLine("Количество дубликатов: {0}", best_prices.Count())
- Console.WriteLine("Хеширование закончено.")
- If best_prices.Count() < 1 Then
- MsgBox("Дубликатов не обнаружено")
- End If
- If best_prices.Count() > 1 Then
- Console.WriteLine("Начато повторное чтение CSV файла и копирование данных {0}", System.DateTime.Now.ToString("HH:mm:ss"))
- Dim outputCSVFileName As String = outputSaveDir.Text & "\" & otputFileName.Text & ".csv"
- Dim outputCSVFile As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(outputCSVFileName, False, System.Text.Encoding.GetEncoding(1251))
- While Not csvReader2.EndOfData
- Try
- currentRow = csvReader2.ReadFields()
- ' Обєднати "комірки" для подальшого запису в файл
- Dim currentString As String = String.Join(";", currentRow)
- Dim id As String = currentRow(2) & currentRow(1)
- ' Якщо ідентифікатор (brand + article) поточного рядка міститься в списку з мінімальними цінами
- If best_prices.ContainsKey(id) Then
- ' і якщо ціна в поточному рядку не дорівню мінімальній ціні, пропустити (не записувати в вихідний файл) його
- If best_prices.Item(id) <> currentRow(7) Then
- Console.WriteLine("ID: {0}, цена {1}. №{2}, article: {3}", id, currentRow(7), csvReader2.LineNumber, currentRow(1))
- Console.WriteLine("Best price: {0}", best_prices.Item(id))
- Continue While
- End If
- End If
- outputCSVFile.WriteLine(currentString)
- Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
- MsgBox("Line " & ex.Message & " is invalid. Skipping")
- End Try
- End While
- outputCSVFile.Close()
- End If
- Console.WriteLine("Конец.")
- End Using
- End Sub
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement