views:

143

answers:

2

I got a strange exception when trying to find out if a property in a list of objects is equal for all objects.

This is my code:

bool lvNoGuests = pvBillData.Reservering.Dagen.All(x =>
{
    return x.AantalKinderen == pvBillData.Reservering.Dagen[0].AantalKinderen &&
           x.AantalVolwassenen == pvBillData.Reservering.Dagen[0].AantalVolwassenen
});

The idea is to use the .All to see if all members of the list have the same value for the two properties as the first entry in the list.

The properties are simple getters (not auto property) and do not modify anything.

When I execute this code, I get an InvalidOperationException "Collection was modified; enumeration operation may not execute".

Anyone got a clue why?

The Lists are not genericht .net lists but are of the type XPCollection (XPO framework of DevExpress).

+3  A: 

Try this:

var eersteDag = pvBillData.Reservering.Dagen[0];
var verwachtAantalKinderen = eersteDag.AantalKinderen;
var verwachtAantalVolwassenen = eersteDag.AantalVolwassenen;

bool lvNoGuests = pvBillData.Reservering.Dagen.All(x =>
{
    return x.AantalKinderen == verwachtAantalKinderen &&
           x.AantalVolwassenen == verwachtAantalVolwassenen
});
Steven
+3  A: 

Is everything a simple getter? Even Dagen? I can only assume that sometihng funky is going on (perhaps with dynamic type creation and silent overrides that you don't see in you code - are the members virtual?). However, to fix it I would try grabbing the particulars into variables:

var first = pvBillData.Reservering.Dagen.First();
var kinderen = first.AantalKinderen;
var volwassenen = first.AantalVolwassenen;
bool lvNoGuests = pvBillData.Reservering.Dagen.All(
    x => x.AantalKinderen == kinderen && x.AantalVolwassenen == volwassenen);
Marc Gravell
Sorry Marc, I beat you on this one ;-)
Steven
@Steven - indeed (+1), but I at least offered some thoughts on what might be happening, and simplified the lambda ;-p
Marc Gravell
.Dagen had indeed a condition in the getter which caused the list to be reloaded from the DB.@Steven, sorry although you and Marc said the same, I'll give him the "answered" points since he was a little bit more explicit.
Henri
D'oh! Van je Nederlandstalige broeders moet je het hebben :-)
Steven
@Steven - "From your brothers need you speak Dutch"? mechanical translation still has a way to go, I suspect...
Marc Gravell
He was complaining that I should have voted his solution as answer since we're both dutch ;)
Henri
Hahaha.. You shouln't bet on Google translate ;-)
Steven