我对 LINQ 和 where 语句有疑问。我有以下代码示例(这是我在应用程序中使用的代码的简化版本):
// Get the images from a datasource.
var images = GetImages(); // returns IEnumerable<Image>
// I continue processing images until everything has been processed.
while (images.Any())
{
// I'm going to determine what kind of image it is and do some actions with it.
var image = images.First();
// Suddenly in my process I'm going to add a where statement to my images collection to fetch all images that matches the specified criteria.
// It can happen (if my images collection is not empty) that the same where statement will be executed again to the images collection.
// This is also where the problem is, somehow when I don't add the ToList() extension method, my linq statement is becoming slow, really slow.
// When I add the ToList() extension method, why is my linq statement running fast again?
var saveImages = images.Where(<criteria>); //.ToList() this is needed to make my LINQ query performant again.
// I'm going to do something with these save images and then I'm going to remove these save images from the current images collection because I do not need to do these anymore by using the following statement.
images = images.Except(saveImages);
}
正如代码示例所解释的,当我添加 ToList() 扩展方法时,为什么我的 LINQ 语句又变快了。为什么我不能只使用 Where 语句,因为它返回一个 IEnumerable 集合?
我真的很困惑,我希望有人可以向我解释:)。