Skip to content

Adding IEnumerable to itself with AddRange results in infinite loop #27389

@joshbartley

Description

@joshbartley

If you have an List, and you use .Where() to filter that list into itself using AddRange, it will loop until the system runs out of memory.

.Net 4.6.1 Behavior "Collection was modified enumeration operation may not execute"
.Net Core 2.1 Behavior OutOfMemoryException

The List has behavior currently for checking if an ICollection is the same reference, the Else fall through does not have this check. Also the Enumerator is being modified but is not throwing an exception, wanted to start a conversation about this since there could be two possible fixes, or this could be new expected behavior different from .Net 4.6.1 or earlier.

Quick sample repo for both 4.6.1 and .Net Core 2.1.

    class Program  
    {
        static void Main(string[] args)
	{
		var testList = new List<TestObject>();
		testList.Add(new TestObject() { Property1 = "test" });
		testList.AddRange(testList.Where(x => x.Property1 == "test"));
	}
    }
    public class TestObject
    {
	public string Property1 { get; set; }
    }

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions