Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Select by LINQ into anonymous type in F#

Tags:

.net

linq

f#

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#?

like image 372
brinch Avatar asked Aug 09 '15 21:08

brinch


People also ask

Do anonymous types work with Linq?

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.

What is anonymous type in LINQ?

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.

Which language integrated query Linq would project an anonymous type?

Anonymous types were introduced in C# 3.0 with Language-Integrated Query (LINQ) expressions.

How do you define anonymous type?

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.


1 Answers

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]} )   
like image 132
myroman Avatar answered Sep 23 '22 15:09

myroman