您需要使用元组来创建
Map
从
List
,因此您根本不需要记录类型。然后,您将要匹配
Map.tryFind
输入国家的。下面是一个使用元组和
地图尝试查找
.我唯一做的其他更改是使用
printfn
而不是
Console.WriteLine
要简化列表生成表达式,请执行以下操作:
open System
open FSharp.Data
let [<Literal>] sampleCsv = @"D:\Country_Capitals.csv"
type Capitals = CsvProvider<sampleCsv, Separators=",", HasHeaders=true>
let readFromCsvFile (fileName:string) =
let data = Capitals.Load(fileName)
[ for row in data.Rows -> (row.Country, row.City) ]
let countryCapitals =
readFromCsvFile sampleCsv
|> Map.ofList
printfn "Find capital by country (type 'q' to quit): "
match Console.ReadLine() with
| "q" -> printfn "Bye!"
| country ->
match countryCapitals |> Map.tryFind country with
| Some capital -> printfn "Capital of %s is %s" country capital
| _ -> printfn "Country not found."
编辑
要显示继续使用记录类型,请执行以下操作:
open System
open FSharp.Data
type CountryCaptial = { Country: string; Capital: string }
let [<Literal>] sampleCsv = @"D:\Country_Capitals.csv"
type Capitals = CsvProvider<sampleCsv, Separators=",", HasHeaders=true>
let readFromCsvFile (fileName:string) =
let data = Capitals.Load(fileName)
[ for row in data.Rows -> { Country = row.Country; Capital = row.City } ]
let countryCapitals =
readFromCsvFile sampleCsv
|> List.map (fun c -> c.Country, c)
|> Map.ofList
printfn "Find capital by country (type 'q' to quit): "
match Console.ReadLine() with
| "q" -> printfn "Bye!"
| country ->
match countryCapitals |> Map.tryFind country with
| Some countryCapital -> printfn "Capital of %s is %s" countryCapital.Country countryCapital.Capital
| _ -> printfn "Country not found."