Reputation: 1344
Consider the following example:
List<String> myList = new List<string>();
myList.Add("Ford");
myList.Add("Porsche");
var filteredList = myList.Where(a => a.StartsWith("F"));
myList.Add("Ferrari");
foreach (string s in filteredList)
{
Console.WriteLine(s);
}
The output is:
Ford
Ferrari
When I create the filtered list, the list only contains:
Ford
Why does modifying the original list affect the filtered one?
Upvotes: 1
Views: 78
Reputation: 56536
LINQ is lazily evaluated. This means that filteredList
does not contain Ford
at the time you create it. All it contains is a reference to myList
and the lambda you gave it. It's when you actually evaluate the list with your foreach
that the filtering happens. Since the list now contains Ferrari
, that is returned as well.
If you want to force the evaluation to happen earlier, you could use ToList()
.
var filteredList = myList.Where(a => a.StartsWith("F")).ToList();
This means that the evaluation will happen right then and there (and not again).
Upvotes: 7
Reputation: 11319
Because your filteredList is not a list. It's an IEnumerable generated by LINQ. It's not a list in of itself, but is a filter that's based off the original.
If you want your filteredList to be an independent list, do this:
var filteredList = myList.Where(a => a.StartsWith("F")).ToList();
Upvotes: 3