-
I have an
IEnumerable<T>when I iterate through it and add it’s element to a list it becomes empty? -
Is there generally anything wrong about what I expect from the code?
public class Apple { private ICollection<Fruit> _fruits = new List<Fruit>(); public void AddFruits(IEnumerable<Fruit> fruits) { if (fruits == null) throw new ArgumentNullException("fruits"); foreach (var fruit in fruits) { _fruits.Add(fruit); } } }The caller code:
public void AddFruits(IEnumerable<Fruit> fruitsToAdd) { foreach (var apple in apples) { // Here fruitsToAdd has elements, fruitsToAdd.ToList() has two fruits. apple.AddFruits(fruitsToAdd); // Here fruitsToAdd has NO element!!, fruitsToAdd.ToList() is empty! // next iteration will not add any fruit to next apple since fruitsToAdd is empty. } }
Update
The ToList() solved the problem. The root of the problem was that the caller to AddFruits(IEnumerable fruitsToAdd) send fruitsToAdd that was like.
fruitsToAdd = obj.Fruits.Except(apples.Fruits);
Each time IEnumerable fruitsToAdd was Rest it run above statement. Which at next iteration run Except and thereby returned no fruits.
The right way is fruitsToAdd = obj.Fruits.Except(apples.Fruits).ToList(); Since we want one evaluation.
Ok, try this:
Without knowing the origin of your
fruitsToAddit’s impossible to say more. SomeIEnumerable<>can’t be re-used. Others can.