0

在 C# 中,您只需使用SelectManywhich 具有重载来保持父对象。你如何在 F# 中做同样的事情?也就是说,我想遍历一组程序集并返回所有具有实现特定属性的类的程序集。

我知道我collect类似于 select many,但我不确定如何在维护父(程序集)信息的同时使用它。

4

2 回答 2

1

您可以通过将 a应用于要为“父”集合的每个元素返回的“子”集合来实现SelectManyusing :collectmap

假设您有一些source并且想要使用getChildren(对于 中的每个元素source)让孩子使用,然后您想使用selectResult同时使用孩子和父母来计算结果,您可以使用以下方式编写以下内容SelectMany

source.SelectMany
  ( (fun parent -> getChildren parent),
    (fun parent child -> selectResult parent child ) )

使用collect,相同的代码如下所示(请注意,该map操作应用于我们传递给的 lambda 函数内部collect-parent仍在范围内):

source |> Seq.collect (fun parent ->
  getChildren parent 
  |> Seq.map (fun child ->
      selectResult parent child ))  

还值得注意的是,SelectMany可以使用 F# 序列表达式来实现捕获的行为 - 也许以更易读的方式 - 如下所示:

seq { for parent in source do 
        for child in getChildren parent do
          yield selectResult parent child }
于 2013-03-19T17:21:43.353 回答
1

看起来你只需要filter而不是collect

let hasTypeWithAttribute<'t when 't :> Attribute> (a: Assembly) = a.GetTypes() |> Array.exists (fun t -> t.GetCustomAttributes(typeof<'t>, true).Length > 0)

let assemblies = inputSet |> Set.filter hasTypeWithAttribute<AttributeName>
于 2013-03-19T17:01:51.910 回答