gpt4 book ai didi

c# - 在 F# 中访问 IEnumerable 中的项目

转载 作者:太空狗 更新时间:2023-10-30 00:57:06 25 4
gpt4 key购买 nike

我尝试在 F# 中使用 Youtube .Net API,但在尝试访问返回到 userPlaylists.Entries 属性的 IEnumerable 时遇到了问题。下面是我测试过的 c# 代码,但是我似乎无法从 f# 中的 IEnumerable 集合返回单个项目。

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

条目解析为类型 IEnumerable<Playlist> Feed<PlayList>.Entries

IEnumerable 似乎在 F# 中表示为一个序列,但我似乎无法弄清楚如何返回正确类型的单个项目,我得到的最接近的是:

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

然而,这似乎返回了一种“播放列表选项”而不是“播放列表”。谁能建议从 IEnumerable 中检索单个项目的正确方法?

最佳答案

Single()如果找不到匹配项,扩展方法将抛出异常,如果找到多个匹配项,它也会抛出异常。 F# Seq 模块中没有直接等效项。最接近的是 Seq.find,它与 .Single() 一样,如果找不到匹配项,将抛出异常,但与 .Single()< 不同 它会在找到匹配项后立即停止查找,如果存在多个匹配项也不会抛出错误。

如果您真的需要“如果有多个匹配则抛出错误”行为,那么最简单的方法就是使用 F# 中的那个确切方法:

open System.Linq

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

如果您不需要“如果多个匹配则抛出”行为,那么您也不应该在 C# 代码中使用 .Single() - .First( ) 会表现得更好,因为它会在找到匹配项后立即停止查找。

如果是我,为了简洁起见,我会使用 Seq.tryFind 而不是 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

我真的很喜欢管道运算符(operator)......

关于c# - 在 F# 中访问 IEnumerable 中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6038073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com