C#将列表合并在一起

时间:2015-07-24 19:16:49

标签: c# linq linq-extensions

我想将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空字段合并。

1 个答案:

答案 0 :(得分:1)

ZIP的工作方式与Aggregate方法类似。说实话,我认为这不是你想要的。

我将向您展示为什么使用ZIP如何工作。鉴于A&amp; B是整数数组。

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

Zipping A&amp; B不会产生:

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

在C#simple中的ZIP在查看两个值后返回一个值。以下是您在.Net 4.0中使用ZIP的功能;

假设我们有以下功能:

Max&amp;最小化并在A&amp ;;上使用Zip B和我想申请Max或Min。这将是结果。

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

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

Zip(A,B, MultiplyFirstBySecond ) = {2, 12}
正如您所见,

ZIP实际上并未合并。它的行为更像聚合,但是跨两个集合而不是一个集合。

你想要的是在你的情况下将一个对象的字段从一个对象合并或复制到另一个对象,从Song Details到Uploaded Song。

我添加了一个可能对您有所帮助的小片段。你给出了很少的实现细节。我假设你不想透露太多关于你项目的detials,那很好:)

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

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

干杯,祝你好运!