Reputation: 3793
I have a List<Product> in memory. It contains all products from my database. This is kept in the Cache.
Depending on the QueryString I need to filter that list of products and bind a repeater to it.
So I am applying a LINQ .Where clause to my list, but as you know the Where returns IEnumerable<Product>
so if I have
var category = "Beverages";
var filteredProducts = allProducts.Where(p => p.Category = category);
what will happen when I call filteredProducts.ToList()?
Note that allProducts is a List<Product>() and contains approx 300 items.
I guess it will create a new List<Product> in memory and will copy the relevant items from allProducts list.
The filteredProducts is approx. 60 items.
How bad in terms of performance is that?
Edit: It is a web app, so we are talking about let's say tens of requests at once to this page and this may affect the performance.
Upvotes: 2
Views: 1568
Reputation: 6674
Felt like writing some silly code for demonstration purposes. The purpose of this demo is for you to see that only references to the objects are copied to the newly created list when calling .ToList()
on your IEnumerable
. So, the underlying objects are the same both in your original list as well as in your new list. This has two implications. First, there was no inefficient deep copy of your objects. Second, changes made to items in the original list and to items in the new list will affect both lists, as the objects are the same in memory. Plop this into a console app to see the output.
class Program
{
class Dog
{
public string name { get; set; }
public bool isAGoodBoy { get; set;}
public Dog(string name, bool isAGoodBoy)
{
this.name = name;
this.isAGoodBoy = isAGoodBoy;
}
}
static void Main(string[] args)
{
List<Dog> doges = new List<Dog>();
doges.Add(new Dog("Rufus", true));
doges.Add(new Dog("Kevin", false)); //chewed furniture
doges.Add(new Dog("Maximus", true));
IEnumerable<Dog> goodBoys = doges.Where(doggy => doggy.isAGoodBoy);
List<Dog> goodBoysList = goodBoys.ToList();
foreach (var goodBoy in goodBoysList) //Iterate over NEW list
{
goodBoy.isAGoodBoy = false; //They wouldn't stop barking
}
//From original list! You'll see all of these will output 'False'
Console.WriteLine("Is Rufus good? " + doges[0].isAGoodBoy.ToString());
Console.WriteLine("Is Kevin good? " + doges[1].isAGoodBoy.ToString());
Console.WriteLine("Is Maximus good? " + doges[2].isAGoodBoy.ToString());
Console.ReadLine();
}
}
Upvotes: 1