Reputation: 715
While debugging my code, I came to know that if you are using a Linq query for assigning any property, whenever that property is used, the query is going to be executed every time. So if you are doing something like:
Myprop= MyList.where(p=>p.Stauts=="ABKI BAAR ..");
So in your code, whenever you do foreach(var prop in Myprop)',
Myprop.ToList().count()` or any use of Myprop, it will result in the execution of the linq query every time.
Isn't executing the linq query everytime it a bad idea, especially when I am not modifying MyList
?
Upvotes: 0
Views: 70
Reputation: 10201
Materialize you query result using .ToArray()
or .ToList()
.
So, instead of
Myprop = MyList.Where(p => p.Status == "ABKI BAAR ..");
Use
Myprop = MyList.Where(p => p.Status == "ABKI BAAR ..").ToArray();
See the MSDN documentation for more information on ToList or ToArray.
You should certainly never write Myprop.ToList().Count()
. That would materialize the query (or copy an already materialized result), count the results, and then throw away the materialized result of the query (or copy thereof). If you only need to count, just do Myprop.Count()
.
Upvotes: 1
Reputation: 28737
You can circumvent this by calling ToList
after your expression:
Myprop = MyList.where(p=>p.Stauts=="ABKI BAAR ..").ToList(); // or .ToArray()
That way it will immediately execute the Linq query and you won't be executing the query every time, since now you have a list.
This obviously does not take into account changes of the source list later on.
Upvotes: 2