Change the property of objects in a List using LINQ

foreach(Beam beam in Beams.Where(x => x.Width > 40))
{
     beam.IsJoist = true;
} 

If your solution must be completely Linq, you could do

Beams.Where(x => x.Width > 40).ToList().ForEach(b => b.IsJoist = true);

However, that is not an ideal way to implement this (@Jacob's answer is a better one). Check out Eric Lippert's blog entry on the topic. The most important lines for me are

The first reason is that doing so violates the functional programming principles that all the other sequence operators are based upon. Clearly the sole purpose of a call to this method is to cause side effects. The purpose of an expression is to compute a value, not to cause a side effect. The purpose of a statement is to cause a side effect.

https://ericlippert.com/2009/05/18/foreach-vs-foreach/

Note that ToList() is called because List<T> provides a ForEach() method, while Linq in general does not offer such an extension method for the reasons Eric Lippert cites in that blog entry.

UPDATE

Your code both updates entities in the original list (changes IsJoist to true for certain conditions) and returns references to the objects that were updated. If that is what you intended, the code functions. However, Linq is designed with a functional paradigm in mind. Introducing side effects within the context of a Linq expression violates the functional programming principal behind the extension methods.


Suppose I want to change value of Property Selected to true for particular object then I can do like this

Beams.Where(x => x.Width > 40).FirstorDefault(z=>z.Selected = true)

Tags:

C#

Linq

List