Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to set values in LINQ?

Tags:

c#

linq

Is there a better way to do these assignments with LINQ?

IEnumerable<SideBarUnit> sulist1 = newlist.Where(c => c.StatusID == EmergencyCV.ID);
foreach (SideBarUnit su in sulist1) su.color = "Red";
like image 434
patrick Avatar asked Oct 20 '11 15:10

patrick


People also ask

Is LINQ to SQL deprecated?

No it is not.

Can we use LINQ on DataSet?

LINQ to DataSet makes it easier and faster to query over data cached in a DataSet object. Specifically, LINQ to DataSet simplifies querying by enabling developers to write queries from the programming language itself, instead of by using a separate query language.


1 Answers

No.

You can do such a thing, as the other answers here point out, but then you are no longer using LINQ.

Eric Lippert wrote an excellent blog post about this very subject, which I highly recommend you read. Here is an excerpt:

I am philosophically opposed to providing such a method, for two reasons.

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 second reason is that doing so adds zero new representational power to the language. Doing this lets you rewrite this perfectly clear code:

foreach(Foo foo in foos){ statement involving foo; }

into this code:

foos.ForEach((Foo foo)=>{ statement involving foo; });

which uses almost exactly the same characters in slightly different order. And yet the second version is harder to understand, harder to debug, and introduces closure semantics, thereby potentially changing object lifetimes in subtle ways.

like image 109
Daniel Pryden Avatar answered Oct 06 '22 01:10

Daniel Pryden