无法在C#中将一个列表附加到另一个列表...尝试使用AddRange

Mat*_*att 8 c# asp.net-mvc list repository addrange

嗨,我正在尝试将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);
Run Code Online (Sandbox Code Playgroud)

我做了调试以检查结果,这是我得到的:resultCollection计数为4 resultCollection2的计数为6,并且在添加范围后,resultCollection仍然只有4,当它应该有10的计数.

谁能看到我做错了什么?任何帮助表示赞赏.

谢谢,
马特

Gre*_*ech 31

当你打电话的时候,ToList()你没有把你的收藏包装在List<T>你正在创建一个List<T>包含相同项目的新集合中.所以你在这里有效地做的是创建一个新的列表,向它添加项目,然后扔掉列表.

你需要做类似的事情:

List<E> merged = new List<E>();
merged.AddRange(resultCollection);
merged.AddRange(resultCollection2);
Run Code Online (Sandbox Code Playgroud)

或者,如果您使用的是C#3.0,只需使用Concat,例如

resultCollection.Concat(resultCollection2); // and optionally .ToList()
Run Code Online (Sandbox Code Playgroud)