Tarek Saied
Tarek Saied

Reputation: 6616

Collection was modified; enumeration operation may not execute. Exception

this code give me and Exception

Collection was modified; enumeration operation may not execute

i use Entity Framework to work with data

            foreach (OfflineMessage omc in _offMsgs)
            {

                var OimDB = new OimDBEntities();

                if (omc.MsgTo == e.MessageData.ToHeader.Uri)
                {
                    var offlineMessage = new OfflineMessage
                    {
                        Delivered = false,
                        MsgContent = omc.MsgContent,
                        MsgFrom = omc.MsgFrom,
                        MsgTime = omc.MsgTime,
                        MsgTo = omc.MsgTo,
                        ID = OimDB.OfflineMessages.NextId(f => f.ID)

                    };

                    oimRepository.InsertOIM(offlineMessage);

                    //InsertData(omc.MsgFrom, omc.MsgTo, omc.MsgContent, omc.MsgTime);
                }
            }
            _toHeader = e.MessageData.ToHeader.Uri;
        }

Upvotes: 1

Views: 1262

Answers (1)

Can Poyrazoğlu
Can Poyrazoğlu

Reputation: 34780

foreach (OfflineMessage omc in _offMsgs)
                {
                    if (omc.MsgTo == _toHeader)
                    {
                        _offMsgs.Remove(omc);
                    }
                }

You are removing elements from the collection while iterating over it. You can't do this. Instead of removing, add them to a temporary list, and after the foreach loop, Remove your items.

Upvotes: 3

Related Questions