Access items in IEnumerable in F #

I am trying to use the Youtube.Net API in F # and I ran into a problem trying to access the IEnumerable returned in the userPlaylists.Entries property. Below is the C # code I tested, however I cannot return individual elements from the IEnumerable collection in f #.

 Feed<Playlist> userPlaylists = request.GetPlaylistsFeed("username");
 var p = userPlaylists.Entries.Single<Playlist>(x => x.Title == "playlistname");

Records are allowed to type IEnumerable<Playlist> Feed<PlayList>.Entries

IEnumerable appears as a sequence in F #, but I can’t figure out how to return a single element of the correct type, the closest I got:

let UserPlaylists = Request.GetPlaylistsFeed("username")
let pl = UserPlaylists.Entries |>
Seq.tryPick(fun x -> if x.Title="playlistname" then Some(x) else None)

However, this seems to return the type “Playlist option” instead of “Playlist”. Can anyone suggest the correct way to extract a single element from IEnumerable?

+3
source share
3 answers

Single() , , , . F # Seq . Seq.find, , .Single(), , , .Single() , , , .

" , ", F #:

open System.Linq

let p = userPlaylists.Entries.Single(fun x -> x.Title = "playlistname")

", ", .Single() # - .First() , , .

, Seq.tryFind over Seq.tryPick " ", .

let userPlaylists = request.GetPlaylistsFeed("username")
let p = userPlaylists.Entries |> Seq.tryFind (fun x -> x.Title = "playlistname")
match p with
| Some pl ->
    // do something with the list
| None ->
    // do something else because we didn't find the list

, , , ...

request.GetPlaylistsFeed("username").Entries
|> Seq.tryFind (fun x -> x.Title = "playlistname")
|> function
   | Some pl ->
       // do something with the list
   | None ->
       // do something else because we didn't find the list

...

+2

Seq.tryPick IEnumerable.FirstOrDefault, , , . Seq.pick IEnumerable.First, , ( , - , IEnumerable.Single), , , Seq.find, IEnumerable.First:

let UserPlaylists = Request.GetPlaylistsFeed "username"
let pl = UserPlaylists.Entries |> Seq.find (fun x -> x.Title = "playlistname")

, IEnumerable.Single, IEnumerable.First, @JoelMueller.

+2

Option.get,

Seq.tryPick(fun x -> if x.Title="playlistname" then Some(x) else None)
|> Option.get

F # ,

let value = Seq.tryPick(fun x -> if x.Title="playlistname" then Some(x) else None)
match value with
| None ->
  // No matching elements.  Take corrective action
| Some value ->
  // The value i'm looking for
+1

All Articles