I don't know what to call this question.This is my example:foreach (var item in lstItem.Where(item => stock.ItemCode == item.ItemCode)){     stock.ItemName = item.ItemName;     stock.ItemUnitName = item.ItemUnitName;     stock.BrandName = item.BrandName;     stock.FamilyName = item.FamilyName;}or // Assume list has itemsvar list = lstItem.Where(item => stock.ItemCode == item.ItemCode);foreach (var item in list){     stock.ItemName = item.ItemName;     stock.ItemUnitName = item.ItemUnitName;     stock.BrandName = item.BrandName;     stock.FamilyName = item.FamilyName;}Which one is better?
foreach in list or foreach in list.where
c#;performance;linq;loops;lambda
There are two interesting questions wrapped into one here.First, is it better to break up more complex expressions into simpler ones, and perhaps take the opportunity to give the variables helpful names?This is often a really good idea, but in this case the code might better read as:var wanted_items = lstItem.Where(item => stock.ItemCode == item.ItemCode);foreach (var item in wanted_items)Second, are there performance issues in breaking up expressions like this?Not so easy to answer, in the general case. In most languages a construct of this kind would lead to all items of the list being processed to filter out those required, and then individual items processed again to apply the assignment. If there is only one match then the first pass will (on average) examine twice as many items as needed.But this is C# and Linq, so now the list will be either an iterator or it will be translated into SQL, both of which optimise processing, to a greater or lesser extent. In this particular case the performance will be (should be) exactly the same whether the expression is split or not, but there are closely related constructs in which splitting the expression like this can crystallise a particular path for execution and have quite severe performance impact.Ultimately, you should always write the most readable code you can using the best possible algorithms and best possible use of underlying framework libraries. If you then have concerns for performance, you need to benchmark and measure before even thinking about changing the code.