如何在F#中处理IEnumerable?

问题描述:

有许多传统接口以纯IEnumerable的形式获取实体的集合.通常,人们会在C#中将对象执行foreach(CertainTypeWeSureItemIs item in items)转换为它们想要的任何类型. IEnumerable不会直接转换为序列.将其包装在seq { for x in xs -> x }中也无济于事,因为它得到了seq{obj}.那么我该如何在F#中执行此操作?

There are quite a few legacy interfaces that get collections of entities in form of plain IEnumerable. Commonly one would do foreach(CertainTypeWeSureItemIs item in items) in C# casting objects to whatever type they want as they go. IEnumerable doesn't translate directly to a sequence. Wrapping it in seq { for x in xs -> x } doesn't help much either because it gets seq{obj}. So how do I do this in F#?

使用Seq.cast<T>:

let al = new System.Collections.ArrayList()
al.Add(1) |> ignore
al.Add(2) |> ignore
al |> Seq.cast<int> |> Seq.iter(printf "%i")