c# - 导致对象实例化并添加到集合的 Zip 列表
问题描述
我有一个Song
具有属性的类Title
和URL
.
我也有两个List<string>
集合,titles
和URLs
,和一个List<Song>
集合,songs
。
我想压缩titles
并URLs
使用 Linq Zip() 并为每次迭代实例化一个新的歌曲对象,其中迭代的标题和 URL 作为其相应的属性,并将结果添加到songs
. 像这样:
List<Song> songs = titles.Zip(URLs, (currentTitle, currentURL) => songs.Add(new Song { Title = currentTitle, URL = currentURL});
我收到以下错误:
错误 CS0411 无法从用法中推断方法“Enumerable.Zip(IEnumerable, IEnumerable, Func)”的类型参数。尝试明确指定类型参数。老Reddit音乐刮板
是否可以通过修复或解决方法来做我想做的事情?
提前致谢。
问候 eheu
解决方案
您可以像这样制作一个列表:
var songs = titles.Zip<string,string,Song>(URLs, (currentTitle, currentURL) => new Song { Title = currentTitle, URL = currentURL });
你也可以省略类型信息,这样:
var songs = titles.Zip(URLs, (currentTitle, currentURL) => new Song { Title = currentTitle, URL = currentURL });
如果歌曲是现有列表,您可以使其工作如下:
songs.AddRange( titles.Zip(URLs, (currentTitle, currentURL) => new Song { Title = currentTitle, URL = currentURL }) );
查看您的编辑后,您可能想要执行以下操作:
List<Song> songs = titles.Zip(URLs, (currentTitle, currentURL) => new Song { Title = currentTitle, URL = currentURL }).ToList();
推荐阅读
- sql - Postgres - 如何选择 jsonb 键值对作为列?
- python - 在 seaborn kdeplot (python) 中为背景着色
- javascript - 如何使用 yarn 将 date-fns JS 库导入 Rails 项目
- sharepoint - 在 SharePoint (PowerApps) 上显示 Azure DevOps 任务/Sprint 统计信息
- android - 运行多个 android 模拟器并使用 Xamarin.Forms 调试信号器应用程序
- laravel - 404 not found file iframe 部署后在 laravel 中显示
- javascript - 缩放文本而不缩放形状
- drag-and-drop - Angular8 - 从拖放区文件中获取文件二进制字符串
- windows - 在自托管 Windows azure devops 代理上运行 docker 容器的权限
- delphi - Delphi CEF 4 未加载某些站点