When working with a System.Collections.Generic.List<'T> in F# and wanting to use F#-specific list functions like List.map and List.head, you'll need to convert the .NET list into an F# list. This is because F#'s List module functions are designed to work with F#'s native, immutable list type, not the mutable .NET List<'T>.
✅ Option: Convert Generic.List<'T> to F# List Using List.ofSeq
F# provides the List.ofSeq function which converts any seq<'T> (including IEnumerable<T>) into an F# list. Since System.Collections.Generic.List<'T> implements IEnumerable<'T>, you can use this function to convert it directly.
let genericList = System.Collections.Generic.List<int>()
genericList.Add(1)
genericList.Add(2)
genericList.Add(3)
// Convert to F# list
let fsharpList = List.ofSeq genericList
// Now use List.map and List.head
let result =
fsharpList
|> List.map (fun x -> x * 2)
|> List.head
This approach is idiomatic in F# and works well for small to moderately sized collections.
⚠️ Important Considerations
- Immutability:
List.ofSeq creates an immutable snapshot of the Generic.List. Any future modifications to the original Generic.List will not affect the F# list.
- Performance: Converting a large
Generic.List to an F# list using List.ofSeq involves copying all elements, which is O(n). If performance is a concern, consider using Seq functions instead.
🔄 Alternative: Use Seq Functions Directly
If you want to avoid converting the entire list and only need to process elements lazily (e.g., to get the head of a mapped sequence), you can use Seq.map and Seq.head directly:
let result =
genericList
|> Seq.map (fun x -> x * 2)
|> Seq.head
This is more efficient if you only need to process a few elements or work lazily, but it doesn't give you the full power of F#'s list operations.
📌 Summary of Options
| Option | Use Case | Efficiency | Notes |
|---|
List.ofSeq + List.map/List.head | Full list processing | O(n) | Idiomatic F#; creates immutable copy |
Seq.map + Seq.head | Lazy processing | O(1) for head | Efficient for large collections; no full conversion |
✅ Recommended Approach
For clarity, immutability, and idiomatic F# code, convert the Generic.List to an F# list using List.ofSeq, then use List.map and List.head as needed.
let result =
genericList
|> List.ofSeq
|> List.map (fun x -> x * 2)
|> List.head
This ensures you're working with F#'s native list type and leveraging the full power of the F# List module.