I have this code snippet, which creates an array of anonymously typed elements with properties Name and 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#. 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#?
You are allowed to use an anonymous type in LINQ. In LINQ, select clause generates anonymous type so that in a query you can include properties that are not defined in the class.
Anonymous types provide a convenient way to encapsulate a set of read-only properties in an object without having to explicitly define a type first. If you write a query that creates an object of an anonymous type in the select clause, the query returns an IEnumerable of the type.
Anonymous types were introduced in C# 3.0 with Language-Integrated Query (LINQ) expressions.
Essentially an anonymous type is a reference type and can be defined using the var keyword. You can have one or more properties in an anonymous type but all of them are read-only. In contrast to a C# class, an anonymous type cannot have a field or a method — it can only have properties.
As in comments, F# doesn't support anonymous type. 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]} )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With