简体   繁体   English

Linq奇怪的行为

[英]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;
}

The problem is that somewhere in your code the definitions collection is modified. 问题是在代码中的某个地方definitions集合被修改了。 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 . 您可以在任何使用definitions地方使用lock来保护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: 并在要修改definitions或其引用的所有位置锁定,例如:

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

or 要么

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

or even 甚至

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

I assume that "CurrentDuration" is a foreach loop variable counter. 我假设“ CurrentDuration”是一个foreach循环变量计数器。

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. foreach语句用于遍历集合以获取所需的信息,但不能用于从源集合中添加,删除或更改项目,以免产生不可预期的副作用。 If you need to add, remove or change items from the source collection, use a for loop. 如果需要从源集合中添加,删除或更改项目,请使用for循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM