2014-02-12 2 views
0

IList 컬렉션에서 N 개의 항목을 제거하고 싶습니다. 다음은 내가 가지고있는 것입니다.술어와 일치하는 N 항목을 IList에서 제거합니다.

public void RemoveSubcomponentsByTemplate(int templateID, int countToRemove) 
{ 
    // TaskDeviceSubcomponents is an IList 
    var subcomponents = TaskDeviceSubcomponents.Where(tds => tds.TemplateID == templateID).ToList(); 

    if (subcomponents.Count < countToRemove) 
    { 
     string message = string.Format("Attempted to remove more subcomponents than found. Found: {0}, attempted: {1}", subcomponents.Count, countToRemove); 
     throw new ApplicationException(message); 
    } 

    subcomponents.RemoveRange(0, countToRemove); 
} 

불행히도이 코드는 광고 한대로 작동하지 않습니다. TaskDeviceSubcomponents는 IList이므로 RemoveRange 메서드가 없습니다. 그래서, .ToList()를 호출하여 실제 List를 인스턴스화하지만, 이는 동일한 컬렉션 항목에 대한 참조가있는 중복 컬렉션을 제공합니다. 하위 구성 요소에서 RemoveRange를 호출해도 TaskDeviceSubcomponents에 영향을주지 않으므로 좋지 않습니다.

간단한 방법이 있나요? 나는 단지 그것을 보지 않고있다.

답변

2

불행히도 각 항목을 개별적으로 제거해야한다고 생각합니다. 나는이에 코드를 변경합니다 : 그것의 일부 항목을 제거하는 동안 TaskDeviceSubcomponents를 반복하지 않도록 여기 ToList을 사용하는 것이 중요합니다

public void RemoveSubcomponentsByTemplate(int templateID, int countToRemove) 
{ 
    // TaskDeviceSubcomponents is an IList 
    var subcomponents = TaskDeviceSubcomponents 
         .Where(tds => tds.TemplateID == templateID) 
         .Take(countToRemove) 
         .ToList(); 

    foreach (var item in subcomponents) 
    { 
     TaskDeviceSubcomponents.Remove(item); 
    } 
} 

하는 것으로. LINQ는 lazy evaluation을 사용하기 때문에 subcomponents을 반복 할 때까지 TaskDeviceSubcomponents을 반복하지 않습니다.

편집

: 나는 단지 countToRemove에 포함 된 항목의 수를 제거 무시, 그래서 WhereTake 전화를했다.

편집 2 : 테이크()에 대한 사양 - 방법 : http://msdn.microsoft.com/en-us/library/bb503062(v=vs.110).aspx

+0

오 감사합니다! .Take()는 실제로 도움이되었습니다. :) –

관련 문제