首页 > 解决方案 > 将列表添加到实例化 C# 上的另一个列表

问题描述

如何将一个列表添加到另一个列表?也许我问的方式不对,但请耐心等待一分钟。我有一个列表,KeyValuePair<string, object>我想将另一个列表成员添加到此列表中。像这样:

var list = new List<KeyValuePair<string, object>>{ new KeyValuePair<string, object>("Screw", "1"),
                                                   new KeyValuePair<string, object>("You", "2"),
                                                   new KeyValuePair<string, object>("Guys", "3")};

var secondList = new List<KeyValuePair<string, object>>{ list, // through error
                                                         new KeyValuePair<string, object>("I'm", "4"),
                                                         new KeyValuePair<string, object>("Going", "5"), 
                                                         new KeyValuePair<string, object>("Home", "6") };

你可以猜到,错误是

无法从 'System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<string, object>>' 转换为 'System.Collections.Generic.KeyValuePair<string, object>'


list在. _ secondList_ secondList那么我该如何实现呢?

标签: c#list

解决方案


Concat 和 ToList LINQ 方法:

var secondList = list.Concat(new List<KeyValuePair<string, object>>{
                                                     new KeyValuePair<string, object>("I'm", "4"),
                                                     new KeyValuePair<string, object>("Going", "5"), 
                                                     new KeyValuePair<string, object>("Home", "6") }).ToList();

推荐阅读