如何在特定字段上使用Map.TryFind?

时间:2018-06-21 04:17:27

标签: f#

因此,我正在将数据映射到底部显示的记录。但是问题是下面指定的代码行。我正在尝试为地图建立索引,并使用Map.TryFind函数返回该地图内的单个字段,但它会输出错误:

Practice2.fsx(299,49): error FS0039: The field, constructor or member 'GrossIncome' is not defined.

我将如何成功地做到这一点?下面是所使用类型的代码。

type GeneralInfo =
    { State : State
      GrossIncome : int }

type FamilyFile = 
    { State : State
      Pets : int
      NumberofChildren : int
      NumberofMembers : int }

type AllData = 
    { State = State
      Month = Month
      Pets  = int
      Children = int
      GrossIncome = int Option }

familyMapgeneralMap的示例:

let generalinfo =
   GeneralCsv.GetSample().Rows
    |> Seq.map (fun row -> 
        { State = row.State |> State
          GrossIncome = row.income })

let generalMap =
    generalinfo
    |> Seq.map (fun x -> x.State,x)
    |> Map.ofSeq

let familyparse=
    FamilyCsv.GetSample().Rows
    |> Seq.map (fun row -> 
        { State = row.State |> State
          Pets = row.pets
          NumberofChildren = row.children
          NumberofMembers = row.familymem  })

let familyMap =
    familyparse
    |> Seq.map (fun x -> x.State,x)
    |> Map.ofSeq

let mapfunc =
    dataMap
    |> Seq.ofList
    |> Seq.map(fun (state,rows) ->
        { State = state
          Month = rows.Month
          Pets = familyMap.[state].Pets
          Children = familyMap.[state].NumberofChildren 
          GrossIncome = generalMap.TryFind(state).GrossIncome <-- Problem Line
          Family = familyMap.[state].NumberofMembers
        })
    |> List.ofSeq

1 个答案:

答案 0 :(得分:2)

您必须使用Option.map

generalMap.TryFind(state) |> Option.map(fun s -> s.GrossIncome)