你好我想追加1个列表到另一个。我以前使用AddRange()完成它,但它似乎没有在这里工作......下面的代码:

IList<E> resultCollection = ((IRepository<E, C>)this).SelectAll(columnName, maxId - startId + 1, startId);                
IList<E> resultCollection2 = ((IRepository<E, C>)this).SelectAll(columnName, endId - minId + 1, minId);
resultCollection.ToList().AddRange(resultCollection2);

我做了调试,检查的结果,这是我的了:resultCollection有4 resultCollection2的数量为6的计数,并添加范围之后,resultCollection仍然只有4个,当它应该有一个数一个数10。

有人能看到我在做什么错?任何帮助表示赞赏。

谢谢,结果 马特

有帮助吗?

解决方案

当你调用ToList()你是不是包裹在集合中List<T>你创建与它相同的项目新List<T>。所以你要有效这里做的是创建一个新的列表,添加项目,然后扔列表了。

你需要做的是这样的:

List<E> merged = new List<E>();
merged.AddRange(resultCollection);
merged.AddRange(resultCollection2);

可替换地,如果您使用C#3.0,只需使用Concat,e.g。

resultCollection.Concat(resultCollection2); // and optionally .ToList()

其他提示

我假设.ToList()是创建一个新集合。因此,你的项目被添加到一个新的集合,立即扔掉原来保持不变。

resultCollection.ToList()将返回一个新的列表。

尝试:

List<E> list = resultCollection.ToList();
list.AddRange(resultCollection2);

尝试

<击>     的IList newList = resultCollection.ToList()的AddRange(resultCollection2)。

List<E> newList = resultCollection.ToList();
newList.AddRange(resultCollection2);

可以使用以下任一的:

List<E> list = resultCollection as List<E>;
if (list == null)
    list = new List<E>(resultCollection);
list.AddRange(resultCollection2);

或者:

// Edit: this one could be done with LINQ, but there's no reason to limit
//       yourself to .NET 3.5 when this is just as short.
List<E> list = new List<E>(resultCollection);
list.AddRange(resultCollection2);

或者:

List<E> list = new List<E>(resultCollection.Concat(resultCollection2));
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top