Кто решил, что этот текстовый файл будет отформатирован с полями фиксированной длины? Всего этого обрезания и дополнения можно избежать с помощью простого файла с разделителями-запятыми или XML-файла или базы данных, которой он действительно принадлежит. Код не проверен. Комментарии и объяснения в строке.
'I assume you have a class that looks something like this
'This uses automatic properties to save you having to
'type a getter, setter and backer field (the compiler adds these)
Public Class Department
Public Property DepartmentID As Integer
Public Property DepartmentHead As String
Public Property DepartmentName As String
Public Property DepartmentBudget As Decimal
End Class
Private Sub BtnBillDept_Click(sender As Object, e As EventArgs) Handles BtnBillDept.Click
Dim DepartmentStore As New Department
'Drag an OpenFileDialog from the ToolBox to your form
'It will appear in the lower portion of the design window
Dim MyFilePath As String = ""
OpenFileDialog1.Title = "Select OrderDetails.Txt"
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
MyFilePath = OpenFileDialog1.FileName
End If
Dim Order() As String = File.ReadAllLines(MyFilePath)
'Changed data type, you use OrderID as an index for the Order array so it must be an Integer
Dim OrderID As Integer
'TryParse will check if you have a valid interger and fill OrderID variable
If Not Integer.TryParse(TxtOrderID.Text, OrderID) Then
MessageBox.Show("Please enter a valid Order ID.")
Return
End If
'EDIT per comment by Codexer
If OrderID > Order.Length - 1 Then
MessageBox.Show("Order Number is too high")
Return
End If
Dim AmountDue As Decimal
If Decimal.TryParse(TxtAmountDue.Text, AmountDue) Then
MessageBox.Show("Please enter a valid Amount Due")
Return
End If
'I hope you realize that the first index in Order is zero
'Mid is an old VB6 method around for compatibility
'Use the .net Substring (startIndex As Integer, length As Integer)
'The indexes in the string start with zero
Dim DeptID As Integer = CInt(Order(OrderID).Substring(5, 4).Trim) '(Trim(Mid(Order(OrderID), 5, 4)))
OpenFileDialog1.Title = "Select DepartmentDetails.txt"
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
MyFilePath = OpenFileDialog1.FileName
End If
Dim DepartmentDetails() As String = File.ReadAllLines(MyFilePath)
Dim DepartmentBudget As Decimal = CDec(DepartmentDetails(DeptID).Substring(35, 6).Trim) '(Trim(Mid(DepartmentDetails(DeptID), 35, 6)))
'You don't need to format anything until you want to display it
'Dim FormattedBudget As String = FormatCurrency(DepartmentBudget, 2)
'A MessageBox returns a DialogResult
Dim YesNo As DialogResult
Dim sw As New StreamWriter(MyFilePath, True)
'Shorcut way to write DepartmentBudget - AmountDue
DepartmentBudget -= AmountDue
'Set the property in the class with the proper data type
DepartmentStore.DepartmentID = DeptID
'Then prepare a string for the writing to the fil
Dim PaddedID = CStr(DeptID).PadLeft(4)
'The .net replacement for LSet is .PadLeft
DepartmentStore.DepartmentHead = DepartmentDetails(DeptID).Substring(5, 20).Trim.PadLeft(20)
DepartmentStore.DepartmentName = DepartmentDetails(DeptID).Substring(25, 10).Trim.PadLeft(20)
'Set the property in the class with the proper data type
DepartmentStore.DepartmentBudget = DepartmentBudget
'Then prepare a string for the writing to the fil
Dim PaddedBudget = CStr(DepartmentBudget).PadLeft(9)
sw.WriteLine(PaddedID & DepartmentStore.DepartmentHead & DepartmentStore.DepartmentName & PaddedBudget)
sw.Close()
'***********************Having Problems Here***********************
'This is using the path from the most recent dialog
DepartmentDetails = File.ReadAllLines(MyFilePath)
'Here you are changing the value of one of the elements in the DepartmentDetails array
DepartmentDetails(DeptID) = ""
'Public Shared Sub WriteAllLines (path As String, contents As String())
'The string "DepartmentDetails" is not a path
File.WriteAllLines(MyFilePath, DepartmentDetails)
'************************Having Problems Here**************************
YesNo = MessageBox.Show("Department has been billed. Would you like to delete the bill?", "Delete Bill?", MessageBoxButtons.YesNo)
If YesNo = DialogResult.Yes Then
End If
End Sub
Обратите внимание на функцию SUBSEQ
.
* (equal (subseq '(1 20 300) 0 2)
'(1 20))
T
Это может быть не сразу очевидно, но в Лиспе индексирование начинается с 0, и вы всегда принимаете полуоткрытое интервалы, так что это берет все элементы списка с индексами в интервале [0, 2).
(defun pncar (n L)
(setq L_ (list (nth 0 L)))
(setq i 0)
(if (and (< n 1) (< n (length L)))
(setq L_ '())
(repeat (- n 1) (progn
(setq i (+ i 1))
(if (/= nil (nth i L))
(setq L_ (append (list (nth i L)) L_))
(setq L_ '())
)
)
)
)
(setq L_ (reverse L_))
)
Примеры:
(pncar 0 '(0 1 2 3))
nil
(pncar 1 '(0 1 2 3))
(0)
(pncar 2 '(0 1 2 3))
(0 1)
(pncar 3 '(0 1 2 3))
(0 1 2)
(pncar 4 '(0 1 2 3))
(0 1 2 3)
(pncar 5 '(0 1 2 3))
nil
Пришлось загрузить командную строку lisp ... но:
(defun head-x (a b)
(loop for x from 1 to a
for y = (car b) do
(setq b (cdr b))
collect y))
итак:
(head-x 2 '(a b c d))
'(a b)
Вышеупомянутый ответ, конечно, совершенно правильный, но обратите внимание, что если вы используете его только для сравнения с другим списком, было бы более эффективно использовать оба списка на месте, вместо того, чтобы составлять новый список для сравнения.
Например, в приведенном выше случае вы можете сказать:
(every #'= '(1 20 300) '(1 20))
=> t
Любовь,
(butlast '(1 20 300) (- (list-length '(1 20 300)) 2))
Should be made into a function/macro.
P.S. This page might be useful. See function 'extrude'.