Skip to content

Instantly share code, notes, and snippets.

@swlaschin
Last active March 7, 2023 22:15
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save swlaschin/9b0f11a5fccc73a8c11f7f7551ef19a9 to your computer and use it in GitHub Desktop.
Save swlaschin/9b0f11a5fccc73a8c11f7f7551ef19a9 to your computer and use it in GitHub Desktop.
C# LINQ -> F# equivalent

F# equivalents to C# LINQ functions

See also https://fsharpforfunandprofit.com/posts/list-module-functions/

Converting each item

// ------------------------------
// add 1 to each item
// ------------------------------
// C#
myList.Select(x => x + 1) 
// F#
myList |> List.map (fun x -> x + 1)

// ------------------------------
// run a method/function for each item
// ------------------------------
// C#
myList.Select(x => ProductId.Create(x) ) 
myList.Select(ProductId.Create)  // alternative without lambda 
// F#
myList |> List.map (fun x -> ProductId.Create x)
myList |> List.map ProductId.Create  // alternative without lambda

// ------------------------------
// wrap each item in a class
// ------------------------------
// C#
myList.Select(x => new ProductId(x) ) 
// F#
myList |> List.map (fun x -> ProductId x)
myList |> List.map ProductId  // alternative without lambda

Converting each item, when it turns into a list of items

myList.SelectMany(x => new[]{x,x} ) 
myList |> List.collect (fun x -> [x]) 

Filter

myList.Where(x => x > 1 ) 
myList |> List.filter (fun x -> x > 1) 

Ordering

myList.OrderBy(x => x) 
myList |> List.sortBy (fun x -> x) 

myList.OrderBy(x => x.LastName).ThenBy(x => x.FirstName)
myList |> List.sortBy (fun x -> x.LastName, x.FirstName)

Testing the contents

myList.Any(x => x > 1 ) 
myList |> List.exists (fun x -> x > 1) 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment