C#使用linq连接两个Collection <string>并获取Collection <string>结果</string> </string>

时间:2010-08-25 18:47:31

标签: c# linq linq-to-objects

我正在尝试这样做:

var collection1 = new Collection<string> {"one", "two"};
var collection2 = new Collection<string> {"three", "four"};

var result = collection1.Concat(collection2);

但结果变量是类型Enumerable [System.String] ,而我想要一个Collection [System.String]

我尝试过施法:

var all = (Collection<string>) collection1.Concat(collection2);

但没有快乐。

2 个答案:

答案 0 :(得分:13)

var result = new Collection<string>(collection1.Concat(collection2).ToList());

由于某种原因,System.Collections.ObjectModel.Collection需要IList参数给它的构造函数。 (其他集合只需要IEnumerator

答案 1 :(得分:4)

使用Enumerable.ToList(),因为List<>ICollection<>

E.g:

IList list = a.Concat(b).ToList()

如果你的意思是System.ObjectModel.Collection<>,那么你必须将创建的列表传递给Collection<>的构造函数,这不是我所知道的。

var collection = new System.ObjectModel.Collection<string>(a.Concat(b).ToList());