Foreach throws an exception, why?

I get this exception:

The collection has been modified; enumeration operation cannot be performed.

when executing this section of code:

List<T> results = new List<T>();
foreach (T item in items)
    if (item.displayText.ToLower().Contains(searchText.ToLower()))
        results.Add(item);
return results;

I do not understand why I am getting this exception, since I am not modifying the contents of the list items.

+3
source share
4 answers

With this, we must ask how the enumeration of “items” is done? Is this a block yield? Using yield blocks can suffer from a ghost of deferred execution (i.e. an Enumerable will not be prepared until access to the enumerator is available), and you may get unexpected results from this.

, , - . , , .

, .

, "" , ..

foreach(var item in items.ToArray())
{
   //your code.
}

, , , something .

, items .ToArray() ( ) foreach.

+3

. , :

lock(items.SyncRoot)
{
    foreach (T item in items)
        ...
}

​​ , .

, , , - ( )?

using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        var items = new List<Item>()
        { 
            new Item() { DisplayText = "A" },
            new Item() { DisplayText = "B" },
            new Item() { DisplayText = "AB" },
        };

        var res = filter(items, "A");
    }

    static List<T> filter<T>(List<T> items, string searchText) where T : Item
    {
        List<T> results = new List<T>();
        foreach (T item in items)
            if (item.DisplayText.ToLower().Contains(searchText.ToLower()))
                results.Add(item);
        return results;
    }
}

class Item
{
    public string DisplayText { get; set; }
}
0

:)

string text = searchText.ToLower();
results = items
  .Where(item => item.displayText.ToLower().Contains(text))
  .ToList();
0

, , . .

: , items of ObservableCollection<T> CollectionChanged, , (-:

-1

Source: https://habr.com/ru/post/1728302/


All Articles