.net - 如何在 F# 中通过 LINQ 选择匿名类型

标签 .net linq f#

我有这个代码片段,它创建了一个匿名类型元素的数组,其中包含属性 Name 和 FirstLetter:

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

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

我想在 F# 中做同样的事情。我试过:
let names = [| "Dennis"; "Leo"; "Paul" |]

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

但这不能编译。它说:

未定义记录标签“名称”。

我怎样才能让这条线在 F# 中工作?

最佳答案

在注释中,F# 不支持匿名类型。因此,如果您想将您的序列投影到另一个序列中,请创建一个记录,它本质上是一个带有命名字段的元组。

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

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

关于.net - 如何在 F# 中通过 LINQ 选择匿名类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31909234/

相关文章:

c# - 如何禁用兼容性 View 设置?

.net - 开发 .net 程序以在 GPU 而不是 CPU 上运行

c# - LinQ 聚合错误 - 序列不包含任何元素

entity-framework - 导航属性上的 EF Core 组

c# - LINQ to Entities 字符串到列的十进制

F# 序列差异

list - F#:创建一个包含所有列表头部的列表,在列表中

c# - 将 DropDownList 中的数据包含到 Gridview 中

javascript - Vue 获取发布数据到 Controller asp.net mvc

string - 硬编码多行字符串的最佳方法是什么?