A191919
A191919

Reputation: 3442

Linq strange behavior

Statment:

(definitions != null && definitions.Where(key => key.asset_id != null &&
                                          key.asset_id == item).FirstOrDefault() != null

Throws:

collection was modified enumeration operation may not execute

How to fix this?

if (definitions != null 
    && definitions
         .Where(key => key.asset_id != null && key.asset_id == item)
         .FirstOrDefault() != null)
{
    CurrentDuration = definitions
                        .Where(key => key.asset_id != null && key.asset_id == item)
                        .FirstOrDefault().duration;
}

Upvotes: 0

Views: 383

Answers (2)

mehrandvd
mehrandvd

Reputation: 9116

The problem is that somewhere in your code the definitions collection is modified. Mostly it's because of collection modification in another thread, but it could have some other reasons. You should find out the piece of code which is modifying collection somewhere else. You can protect the definitions variable using a lock wherever you're using definitions.

if (definitions != null)
{
    lock (definiitons)
    {
        var definition = definitions.FirstOrDefault(key => key.asset_id != null && key.asset_id == item);
        if (definition != null)
            CurrentDuration = definition.duration;
    }
}

and put lock everywhere you're modifying the definitions or its references, for example:

lock (definitions)
{
    definitions.Add(x);
}

or

lock (definitions)
{
    definitions.Remove(x);
}

or even

var otherRef = definitions
lock (otherRef )
{
    otherRef .Add(x);
}

Upvotes: 5

Ehsan.Saradar
Ehsan.Saradar

Reputation: 704

I assume that "CurrentDuration" is a foreach loop variable counter.

The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add ,remove or change items from the source collection to avoid unpredictable side effects. If you need to add, remove or change items from the source collection, use a for loop.

Upvotes: 0

Related Questions