【问题标题】:Join 2 list of recoreds based on same label in f#在 f# 中加入 2 个基于相同标签的记录列表
【发布时间】:2019-07-04 16:47:34
【问题描述】:

我有 2 个具有相同标签 id1 的记录列表。我需要一种加入他们的方式。

type A = { id1: int; name: string }

type B = { id1: int; id2: Option<int> }

let a1 = { id1 =  1; name = "nafis" }
let a2 = { id1 =  2; name = "habib" }

let b1 = { id1 = 1; id2 = Some(5) }
let b2 = { id1 = 1; id2 = None }
let b3 = { id1 = 2; id2 = None }

let a = [a1; a2]
let b = [b1; b2; b3]

printfn "%A" a =>  [({id1 = 1;name = "nafis";}, {id1 = 2;name = "habib";})]
printfn "%A" b =>  
[({id1 = 1; id2 = Some 5;}, {id1 = 1; id2 = None;}, {id1 = 2;id2 = None;})]

如何加入这两个基于id1 的列表?

我想要这样的输出 =>

[({id1 = 1;name = "nafis"; id2 = [Some 5; None];}, {id1 = 2;name = "habib"; id2 =[None];})]

某种形式的教程或博客链接会有所帮助。

【问题讨论】:

  • this question 有帮助吗?
  • 不,我无法创建项目列表。列表ab 是不同的类型。
  • 没有什么神奇的方法可以将两种任意类型合并在一起。您只需定义合并类型并自己编写转换代码。除非您可以更具体地说明您遇到的任何问题,否则我认为这个问题太宽泛了。
  • F# 查询表达式有一个 join 运算符:docs.microsoft.com/en-us/dotnet/fsharp/language-reference/… - 不过,您必须自己创建“连接类型”以及处理连接结果。

标签: f# list-manipulation


【解决方案1】:

MSDN: 查询表达式使您能够查询数据源并将数据放入所需的形式。查询表达式为 F# 中的 LINQ 提供支持。

正如 cmets 中正确提到的,您需要有第三种类型 C 来承载连接的结果,然后使用良好的旧 LINQ 来连接列表:

type A = { id1: int; name: string }
type B = { id1: int; id2: Option<int> }
type C = { id1: int; name: string; id2: Option<int> }

let a1 = { id1 =  1; name = "nafis" }
let a2 = { id1 =  2; name = "habib" }

let b1 = { id1 = 1; id2 = Some(5) }
let b2 = { id1 = 1; id2 = None }
let b3 = { id1 = 2; id2 = None }

let a = [a1; a2]
let b = [b1; b2; b3]

let result (a:A list) (b: B list) = query {
    for list1 in a do
    join list2 in b on
        (list1.id1 = list2.id1)
    select {id1 = list1.id1; name = list1.name; id2= list2.id2}
}

let c = result a b |> List.ofSeq

结果:

val c : C list = [{id1 = 1;
               name = "nafis";
               id2 = Some 5;}; {id1 = 1;
                                name = "nafis";
                                id2 = None;}; {id1 = 2;
                                               name = "habib";
                                               id2 = None;}]

【讨论】:

    猜你喜欢
    • 2020-06-24
    • 1970-01-01
    • 2017-11-27
    • 2011-11-27
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    • 2021-11-13
    • 1970-01-01
    相关资源
    最近更新 更多