c# - Why IEnumerable becomes empty after adding elements to a collection? -



c# - Why IEnumerable<T> becomes empty after adding elements to a collection? -

i have ienumerable<t> when iterate through , add together it's element list becomes empty?

is there wrong expect 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 2 fruits. apple.addfruits(fruitstoadd); // here fruitstoadd has no element!!, fruitstoadd.tolist() empty! // next iteration not add together fruit next apple since fruitstoadd empty. } }

update

the tolist() solved problem. root of problem caller addfruits(ienumerable fruitstoadd) send fruitstoadd like.

fruitstoadd = obj.fruits.except(apples.fruits);

each time ienumerable fruitstoadd rest run above statement. @ next iteration run except , thereby returned no fruits.

the right way fruitstoadd = obj.fruits.except(apples.fruits).tolist(); since want 1 evaluation.

ok, seek this:

public void addfruits(ienumerable<fruit> fruitstoadd) { var fruitstoaddcopy = fruitstoadd.tolist(); // add together line foreach (var apple in apples) { apple.addfruits(fruitstoaddcopy); // , alter } }

without knowing origin of fruitstoadd it's impossible more. ienumerable<> can't re-used. others can.

c# linq generics ienumerable

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

intellij idea - Update external libraries with intelij and java -

javascript - send data from a new window to previous window in php -