-2

我想将 songDetails 和 savedSongs 的字段合并在一起。我该怎么做呢?我听说过,.Zip()但我不确定如何使用它。

    [HttpPost]
    public ActionResult Upload(IEnumerable<UploadedSong> songDetails)
    {
        IEnumerable<UploadedSong> savedSongs = (IEnumerable<UploadedSong>)(Session["UserSongs"]);            

        return View();
    }

编辑: songDetailssavedSongs有字符串字段:Category、AlbumName、BandName,但是在 songDetails 这些有数据。所以我想将这些非空数据字段与同一个索引中的 savedSongs 空字段合并。

4

1 回答 1

1

ZIP 的工作方式类似于聚合方法。老实说,我认为这不是你想要的。

我将通过一个示例向您展示 ZIP 的工作原理。给定 A 和 B 是整数数组。

var A = new [] { 1, 3 };
var B = new [] { 2, 4 };

压缩 A & B 不会产生:

C = {1, 2, 3 ,4};

C# simple 中的 ZIP 在查看两个值后返回一个值。这是您可以在 .Net 4.0 中使用 ZIP 执行的操作;

假设我们有以下功能:

Max & Min 并在 A & B 上使用 Zip,我想应用 Max 或 Min。这将是结果。

Zip(A,B, Max) = { 2, 4}
Zip(A,B, Min) = { 1, 3}

如果我有另一个名为 MultiplyFirstBySecond 的函数,我会得到:

Zip(A,B, MultiplyFirstBySecond ) = {2, 12}

如您所见,ZIP 实际上并没有合并。它的行为更像 Aggregate,但跨越两个集合而不是一个。

在您的情况下,您想要将字段从一个对象合并或复制到另一个对象,从歌曲详细信息到上传的歌曲。

我已经包含了一个可能对您有所帮助的小片段。您提供的实施细节很少。我假设你不想透露太多关于你的项目的细节,这很好:)

无论如何,这是我试图帮助你的尝试。

using System.IO;
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{ 
    class UploadedSong { 
        public string Author{get;set;}
        public string Name{get;set;}
        public float Length{get;set;}
        public string Path{get;set;}
        public byte[] SizeInBytes{get;set;}
    }

    public void UpdateSongDetails(IEnumerable<UploadedSong> uploadedSongs, IEnumerable<UploadedSong> songDetails) { 
        // Note that this might blow up if you have duplicate song names
        // You gave very little to work with so my preconditions are weak

        var lookupDetails = songDetails.ToDictionary(song => song.Name, song => song);

        foreach(var uploadedSong in uploadedSongs) {
            var key = uploadedSong.Name;
            if(lookupDetails.ContainsKey(key)) {
                var details = lookupDetails[key];
                uploadedSong.Author = details.Author; 
                // ... more details here
            }
        }
    }

    static void Main()
    {
        // I am assuming that song details is something you populate from some reliable source
        // but for simpilicity I will just declare it.
        var songDetails = new List<UploadedSong>(); 
        var uploadedSongs = (IEnumerable<UploadedSong>)(Session["UserSongs"]);
        UpdateSongDetails(uploadedSongs, songDetails);
    }
}

干杯和好运!

于 2015-07-24T20:13:35.507 回答