C#에서 한 목록을 다른 목록에 추가 할 수 없습니다… AddRange를 사용하려고합니다.

StackOverflow https://stackoverflow.com/questions/1724606

문제

안녕하세요 저는 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 카운트는 10이지만 카운트는 10입니다.

누구든지 내가 뭘 잘못하고 있는지 볼 수 있습니까? 모든 도움이 감사합니다.

감사,
매트

도움이 되었습니까?

해결책

전화 할 때 ToList() 당신은 컬렉션을 a로 포장하지 않습니다 List<T> 당신은 새로운 것을 창조하고 있습니다 List<T> 동일한 항목이 있습니다. 따라서 여기서 효과적으로하고있는 일은 새 목록을 만들고 항목을 추가 한 다음 목록을 버리는 것입니다.

다음과 같은 작업을 수행해야합니다.

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

또는 C# 3.0을 사용하는 경우 간단히 사용하십시오. Concat, 예를 들어

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