Reputation: 69
I need to remove an element from a list<> in C#. From the previous answers provided, it seems that one has to loop backwards through the collection to achieve this. But, I have an IEnumerator to iterate through elements of the list. The code is as follows:
IEnumerator<Solution> iterator = solutionsList_.GetEnumerator();
while (iterator.MoveNext())
{
Solution element = iterator.Current;
int flag = dominance_.Compare(solution, element);
if (flag == -1) { // The Individual to insert dominates other
// individuals in the archive
iterator.Remove();} // Delete it from the archive
It would be very helpful if I could get some way of removing the element from the list<> along with using the enumerator.
Upvotes: 2
Views: 2703
Reputation: 27377
Since you have a List<T>
, then there's no reason to explicitly grab the enumerator. You can just use a regular loop, and go backwards - and you'll be able to remove elements without any issue, here is a code sample:
var solutionsList_ = new List<int>();
for (var i = solutionsList_.Count - 1; i >= 0; i--)
{
var element = solutionsList_[i];
//if (Some logic)
{
solutionsList_.RemoveAt(i);
}
}
Upvotes: 3
Reputation: 29036
I think You are complicating the scenario. You can Directly apply LINQ extension methods over List
. So You can simply use the following code to remove the Items from the List:
List<Solution> solutionsList_ = new List<Solution>() { };
// Populate the list here
var itemsToRemove = solutionsList_.Where(x => dominance_.Compare(solution, x) == -1);
foreach (var item in itemsToRemove)
{
solutionsList_.Remove(item);
}
Upvotes: 0
Reputation: 2392
IEnumerable's can only been enumerated, you cannot add/remove an item from it.
You can use an ICollection to add/remove items, you can try casting your IEnumerable to an ICollection as List implements ICollection.
http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx
Upvotes: 2