使用另一个c#填充一个List

时间:2017-07-17 20:21:54

标签: c# .net arraylist

我有一个List<Song>,其中歌曲类有string Titlestring Artiststring Image。虽然我有3 Lists<string>TitlesArtistsImages。如何在没有循环的情况下使用这3个列表填充List?

我不需要循环,因为列表太长而且需要10秒钟才能完成。在这种情况下,异步操作并不合适。

修改

    private Task GetPopularSongsAsync()
    {
        return Task.Run(() => 
        {
            var html = WebManager.GetPageAsync("http://myzuka.me/");
            html.Wait();

            var document = new HtmlParser().Parse(html.Result);

            var titles = document.DocumentElement.QuerySelectorAll(".player-inline p a");
            var artists = document.DocumentElement.QuerySelectorAll(".player-inline .details");
            var ids = document.DocumentElement.QuerySelectorAll(".player-inline").Select(m => m.GetAttribute("id")).ToList();


            for (int i = 0; i <= 20; i++) // 20 is a random number for testing. It's usualy near 300-500
            {
                var newSong = new Song()
                {
                    Title = titles[i].InnerHtml,
                    Artist = GetArtistsFromInstance(artists[i].QuerySelectorAll("a.strong")),
                    Size = "12.3",
                    Bitrate = 320,
                    Length = 12.3,
                    Id = Regex.Replace(ids[i], @"[^\d]", "").Trim()
                };

                Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    NewSongs.Add(newSong);
                });
            }
        });
    }

3 个答案:

答案 0 :(得分:1)

你的代码有很多问题。首先关闭您正在使用异步/等待错误

async / await 99%的时间你希望//Marked the method as async private async Task GetPopularSongsAsync() { //Now we can await the async method var html = await WebManager.GetPageAsync("http://myzuka.me/"); var document = new HtmlParser().Parse(html.Result); var titles = document.DocumentElement.QuerySelectorAll(".player-inline p a"); var artists = document.DocumentElement.QuerySelectorAll(".player-inline .details"); var ids = document.DocumentElement.QuerySelectorAll(".player-inline").Select(m => m.GetAttribute("id")).ToList(); for (int i = 0; i <= ids.Length; i++) { var newSong = new Song() { Title = titles[i].InnerHtml, Artist = GetArtistsFromInstance(artists[i].QuerySelectorAll("a.strong")), Size = "12.3", Bitrate = 320, Length = 12.3, Id = Regex.Replace(ids[i], @"[^\d]", "").Trim() }; //No need to run a task to add to the list, just add it NewSongs.Add(newSong); } } 一直在你的调用堆栈中。看看下面的代码:

df.write.format("es").save("db/test")

现在你不应该陷入困境。从那里你可以

你应该看看best practices for async/await

答案 1 :(得分:0)

你在这里遗漏了很多细节。我将假设标题,艺术家和图像的长度与各自列表中相同索引的Song组件的长度相同,并提供以下解决方案供您考虑:

Song[] songs = new Song[Titles.Length];
Parallel.For(0, Titles.Length,
               index => 
                {
                    songs[index] = new Song
                    {
                        Title = Titles.ElementAt(index),
                        Artist = Artists.ElementAt(index),
                        Image = Images.ElementAt(index)
                    }
                });
return songs.ToList();

答案 2 :(得分:0)

下面的代码应该可行,但我必须错过一个关键要求;也就是说,标题,艺术家和图像是如何相关的?否则,它只是一个巨大的笛卡尔联盟。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lists
{
    public class Song
    {
        public string Title;
        public string Artist;
        public string Image;

        public override string ToString()
        {
            return string.Format( "Title = {0}, Artist = {1}, Image = {2}", Title, Artist, Image.Replace("https://en.wikipedia.org/wiki/File:", string.Empty) );
        }
    }

    public class Program
    {
        static void Main( string [] args )
        {
            List< string > titles = new List< string > { "Dazed And Confused", "Iron Man", "Young Lust" };
            List< string > artists = new List< string > { "Led Zeppelin", "Black Sabbath", "Pink Floyd" };
            List< string > images = new List< string > { 
                "https://en.wikipedia.org/wiki/File:Led_Zeppelin_-_Led_Zeppelin_(1969)_front_cover.png", 
                "https://en.wikipedia.org/wiki/File:Black_Sabbath_-_Paranoid.jpg", 
                "https://en.wikipedia.org/wiki/File:PinkFloydWallCoverOriginalNoText.jpg"
            };

            var songs = titles.SelectMany(
                t => artists.SelectMany(
                    a => images,
                    ( a, i ) => new Song { Title = t, Artist = a, Image = i } ) );

            foreach ( var song in songs )
            {
                Console.WriteLine( song );
            }
            Console.Read();

        }
    }
}