首页 > 解决方案 > 导致对象实例化并添加到集合的 Zip 列表

问题描述

我有一个Song具有属性的类TitleURL.

我也有两个List<string>集合,titlesURLs,和一个List<Song>集合,songs

我想压缩titlesURLs使用 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

标签: c#.netlinqcollections

解决方案


您可以像这样制作一个列表:

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();


推荐阅读