简体   繁体   English

如何通过LINQ选择F#中的匿名类型

[英]How to Select by LINQ into anonymous type in F#

I have this code snippet, which creates an array of anonymously typed elements with properties Name and FirstLetter: 我有这段代码片段,它创建了一个匿名类型元素数组,其中包含Name和FirstLetter属性:

string[] arr = { "Dennis", "Leo", "Paul" };

var myRes = arr.Select(a => new { Name = a, FirstLetter = a[0] });

I would like to do the same in F#. 我想在F#中做同样的事情。 I tried: 我试过了:

let names = [| "Dennis"; "Leo"; "Paul" |]

let myRes = names.Select(fun a -> {Name = a; FirstLetter = a[0]} )

But this doesn't compile. 但这不编译。 It says: 它说:

The record label 'Name' is not defined. 未定义记录标签“名称”。

How can I get this line to work in F#? 如何让这条线在F#中工作?

As in comments, F# doesn't support anonymous type. 与评论一样,F#不支持匿名类型。 So if you want to project your sequence into another sequence, create a record, which is essentially a tuple with named fields. 因此,如果您想将序列投影到另一个序列中,请创建一个记录,它实际上是一个带有命名字段的元组。

type p = { 
  Name:string;
  FirstLetter: char 
}

let names = [| "Dennis"; "Leo"; "Paul" |]
let myRes = names.Select(fun a -> {Name = a; FirstLetter = a.[0]} )   

Your initial attempts would work more intuitively as of F# 4.6. 从F#4.6开始,您的初始尝试将更直观。 Testing a similar example using .NET Core SDK 3.0.100-preview4 I was able to prove this out using the new Anonymous Record feature. 使用.NET Core SDK 3.0.100-preview4测试类似的示例我能够使用新的匿名记录功能证明这一点。

let names = [| "Dennis"; "Leo"; "Paul" |]

let myRes = names.Select(fun a -> {| Name = a; FirstLetter = a.[0] |})

Notice the use of the | 注意使用| character on the insides of the curly braces. 花括号内侧的字符。 This is what now distinguishes regular records from anonymous records in F#. 这就是现在将常规记录与F#中的匿名记录区分开来的原因。 Also notice that when accessing the first character of a string in F# that the . 另请注意,当访问F#中的字符串的第一个字符时. method accessor operator must be used to access the indexer just like when accessing other methods. 必须使用方法访问器运算符来访问索引器,就像访问其他方法一样。

let names = [| "Dennis"; "Leo"; "Paul" |]
let myRes = names.Select(fun a -> a, a.[0])
for r in myRes do
    let name, firstletter = r
    printfn "%A, %A" name firstletter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM