Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LINQ to Update A Property in a List of Entities

Tags:

linq

Say I have an entity that looks something like this simple example:

MyEntity  {    int property1;    int property2;    int property3; } 

Now assume I have an IEnumerable list of these entites. Is there a LINQ query I can execute that would set the value of property1 to 100 for each entity in the list? I know I can do this via a foreach, but was wondering if LINQ could do this more elegantly.

like image 344
Randy Minder Avatar asked Nov 21 '09 19:11

Randy Minder


People also ask

How do you update a record in LINQ?

You can update rows in a database by modifying member values of the objects associated with the LINQ to SQL Table<TEntity> collection and then submitting the changes to the database. LINQ to SQL translates your changes into the appropriate SQL UPDATE commands.

Can LINQ query work with Array?

Yes it supports General Arrays, Generic Lists, XML, Databases and even flat files. The beauty of LINQ is uniformity.

Is LINQ to SQL deprecated?

No it is not.


2 Answers

Like this:

var result = GetMyIEnumerable()                 .ToList(); result.ForEach(x => x.property1 = 100); 
like image 132
Bruno Reis Avatar answered Oct 03 '22 05:10

Bruno Reis


To Darin's point, LINQ is built for querying. I've gotten into the mindset when working with LINQ that objects being queried should be treated as immutable. However, the Select operator is also great for transformations.

So, you could solve your problem by transforming from one set to another as follows:

var result = myEntityCollection.Select(e => {    var ret = e;    e.property1 = 100;    return e; }); 

The items in the original collection are untouched, but the items in result will now all have property1 set to 100.

like image 41
mkedobbs Avatar answered Oct 03 '22 03:10

mkedobbs