我需要输入一份额外的食物(酱料和一顿饭)及其各自的价格。通过老师的一些代码,我能够读取文件,将额外的名称和价格放入列表中,然后显示它已经有效。现在问题出现了,我必须按字母顺序对附加内容进行排序,以便能够对其应用二进制搜索。我已尝试使用.sort和OrderBy等所有内容,但没有任何作用。
带有数据的外部文本文件
鹰嘴豆泥,0.75
辣椒,0.50
Tabouli,1.25
Tzatziki,0.50
额外的公共课
Public Class extra
Public Property Name As String
Public Property Price As Decimal
End Class
此代码导入数据并将其放入列表
Dim allExtras = From line In System.IO.File.ReadLines("C:\Users\ExtrasList.txt")
Let Columns = line.Split(","c)
Where Columns.Length = 2
Let Price = Decimal.Parse(Columns(1).Trim())
Let Name = Columns(0).Trim()
Select New extra With {.Name = Name, .Price = Price}
Dim extraList As List(Of extra) = allExtras.ToList()
显示列表
Console.WriteLine()
Console.WriteLine("Extra Name" & vbTab & "Price")
Console.WriteLine("-----------" & vbTab & "-----")
For Each extra In extraList
Console.WriteLine(extra.Name & vbTab & vbTab & extra.Price)
Next
我只需要将额外内容及其价格从单独的文件中获取到可以按字母顺序排序的数组或列表中,以便用户可以搜索以查看是否存在他们想要的额外内容。我还需要能够访问列表,以便用户可以选择和额外,然后将所需的价格添加到总价格中。任何帮助将不胜感激,因为这部分阻止我进一步发展。我不介意,如果有人能够帮助我使用现有代码对列表进行排序,或者向我展示一种更有效的方式将文件中的数据读入列表,我只需要某种解决方案。
答案 0 :(得分:0)
Imports System.Linq
. . . . . .
' I think, this is cleaner way to load list
Dim eList as List(Of Extra) = File.ReadAllLines("C:\Users\ExtrasList.txt").
Select(
Function(l)
Dim a() As = l.Split(",".ToCharArray())
Return New Extra With { .Name = a[0].Trim(), .Price = Decimal.Parse(a(1).Trim()) }
End Function).ToList()
......
' Check if extra exists. Optionally, you can use string comparison options
If (eList.Any(Function(i) String.Equals(i.Name, "The Name")) Then
......
' get price of specific extra
Dim price As Decimal = eList.Single(Function(i) String.Equals(i.Name, "The Name")).Price
答案 1 :(得分:0)
按名称搜索和按名称获取价格的最有效方式是将名称和代理价格添加到Dictionary
Dim sauces = File.ReadAllLines("C:\Users\ExtrasList.txt").
Select(Function(line) line.Split(",")).
ToDictionary(Function(pair) pair(0), Function(pair) pair(1))
然后你可以使用它
Dim price As String
If sauces.TryGetValue("Hummus", price) = True Then
' Use price
Else
' Show not found message
End If
对于列表,您可以遍历所有价值密钥对
Dim orderedPairs = sauces.OrderBy(Function(pair) pair.Key)
For Each sauce As KeyValuePair(Of String, String) In orderedPairs
Dim name = sauce.Key
Dim price = sauce.Value
Next
我建议用适当类型的酱汁创建自己的类
Public Class Sauce
Public Property Name As String
Public Property Price As Decimal
End Class
然后,您可以通过引入自己的方法将行转换为Sauce
Public Function LineToSauce(line As String) As Sauce
Dim pair As String() = line.Split(",")
Return New Sauce With
{
.Name = pair(0),
.Price = Decimal.Parse(pair(1))
}
End Function
' Reading
Dim sauces = File.ReadAllLines("C:\Users\ExtrasList.txt").
Select(AddressOf LineToSauce).
ToDictionary(Function(sauce) sauce.Name)
' searching by name
Dim sauce As Sauce
If sauces.TryGetValue("Hummus", sauce) = True Then
' Use sauce.Price or sauce.Name
Else
' Show not found message
End If
' iterating and ordering
Dim orderedSauces = sauces.Values.OrderBy(Function(sauce) sauce.Name)
For Each sauce As orderedSauces
Dim name = sauce.Name
Dim price = sauce.Price
Next