在IEnumerable上使用Seq函数 [英] Using Seq functions on an IEnumerable
问题描述
我正在尝试在IEnumerable上应用Seq函数.更具体地说,是实现ICollection
和IEnumerable
的System.Windows.Forms.HtmlElementCollection
.
I'm trying to apply Seq functions on an IEnumerable. More specifically, it's System.Windows.Forms.HtmlElementCollection
which implements ICollection
and IEnumerable
.
由于F#seq
是IEnumerable,所以我认为我可以写
Since an F# seq
is an IEnumerable, I thought I could write
let foo = myHtmlElementCollection |> Seq.find (fun i -> i.Name = "foo")
,但是编译器将一无所有,并抱怨类型'HtmlElementCollection'与类型'seq<'a>'" 不兼容.
but the compiler will have none of it, and complains that "The type 'HtmlElementCollection' is not compatible with the type 'seq<'a>'".
但是,编译器愿意在for .. in ..
序列表达式中接受IEnumerable:
However, the compiler willingly accepts the IEnumerable in a for .. in ..
sequence expression:
let foo = seq { for i in myHtmlElementCollection -> i } |> Seq.find (fun i -> i.Name = "foo")
我需要做些什么才能使IEnumerable像任何旧的F#seq
一样被对待?
What do I need to do in order for the IEnumerable to be treated just like any old F# seq
?
注意::该问题被标记为重复,但并非如此.链接的重复"是关于 untyped 序列(来自seq {for ...}表达式的seq),而我的问题是关于 typed 序列.
NB: This question is marked as a duplicate, but it's not. The linked "duplicate" is about untyped sequences (a seq from the seq { for ... } expression), whereas my question is about typed sequences.
推荐答案
F#的类型seq<'a>
等同于泛型 IEnumerable
.您可以使用 Seq.cast<'a>
函数将非通用的转换为通用的:
F#'s type seq<'a>
is equivalent to the generic IEnumerable<'a>
in System.Collections.Generic
, but not to the non-generic IEnumerable
. You can use the Seq.cast<'a>
function to convert from the non-generic one to the generic one:
let foo = myHtmlElementCollection
|> Seq.cast<HtmlElement>
|> Seq.find (fun i -> i.Name = "foo")
这篇关于在IEnumerable上使用Seq函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!