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.
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.
Yes it supports General Arrays, Generic Lists, XML, Databases and even flat files. The beauty of LINQ is uniformity.
No it is not.
Like this:
var result = GetMyIEnumerable() .ToList(); result.ForEach(x => x.property1 = 100);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With