I have following code that populates a System.Collections.Generic.List I don't like it so I was wondering if there is a better way to do this.
let getDirectories =
Directory.GetDirectories(_baseFolder)
let languagesList = new System.Collections.Generic.List<string>()
Seq.cast getDirectories
|> Seq.map(fun dir -> (new DirectoryInfo(dir)).Name)
|> fun range -> languagesList.AddRange(range)
-
Have you tried:
let list = new System.Collections.Generic.List<string>(arr)
List<'T>
has a constructor that takes anIEnumerable<'T>
so it happily takes anyseq<'T>
you pass to it.: +1 he he (embaracced) ok now I shall punish myself. -
In addition to Mehrdad's answer
I find it helpful to define helper modules for many standard collections and .Net types to make them more F# friendly. Here I would define the following
module BclListUtil = let ofArray (arr: 'T array) = new System.Collections.Generic.List<'T>(arr) let ofSeq (arr: 'T seq) = new System.Collections.Generic.List<'T>(arr)
Then you could change your original code to the following
let getDirectories = Directory.GetDirectories(_baseFolder) let languagesList = getDirectiories |> Seq.map (fun dir -> (new DirectoryInfo(dir)).Name) |> BclListUtil.ofSeq
kvb : Note also that you can use the shorter (and potentially less ambiguous) type abbreviation `ResizeArray<_>` instead of `System.Collections.Generic.List<_>`.JaredPar : @kvb, thanks, I didn't realize there was already a type alias present. -
The F# alias for
System.Collections.Generic.List<_>
isResizeArray<_>
as kvb noted. The F# PowerPack includes a ResizeArray module for working with BCL Lists in an idiomatic F# fashion similar to the Seq and List modules.However, for some strange reason this module seems to include
ofArray
andofList
andtoSeq
but notofSeq
.
0 comments:
Post a Comment