如何将列表添加到另一个列表?也许我以错误的方式提出要求,但请耐心等待一分钟。我有一个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 '
对我来说,在list
的实例化中向secondList
添加secondList
很重要。那我该如何实现呢?
答案 0 :(得分:3)
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();
答案 1 :(得分:1)
使用AddRange方法System.Collections.Generic
secondList.AddRange(list)
或者只是使用foreach并自行完成
foreach(var item in list)
{
secondList.Add(item)
}