Randy Minder
Randy Minder

Reputation: 48402

Using LINQ to Update A Property in a List of Entities

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.

Upvotes: 79

Views: 142652

Answers (5)

Dani
Dani

Reputation: 2036

In addition to Darrelk and mkedobbs, VB.NET Code:

object.list =
    object.list.Select(Function(x)
                           x.property = If(x.property.Length > 3, x.property.Substring(0, 3), x.property)
                           Return x
                       End Function).ToList()

Upvotes: 0

Darrel K.
Darrel K.

Reputation: 1729

Here are two solutions that I found that worked for me.

result = result.Where(x => (x.property1 = 100) == 100).ToList();

or

result = result.Select(c => { c.property1 = 100; return c; }).ToList();

Upvotes: 26

Bruno Reis
Bruno Reis

Reputation: 37822

Like this:

var result = GetMyIEnumerable()
                .ToList();
result.ForEach(x => x.property1 = 100);

Upvotes: 171

mkedobbs
mkedobbs

Reputation: 4375

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.

Upvotes: 18

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

If you have 100 properties maybe reflection would be most elegant. LINQ's for querying not updating.

Upvotes: 5

Related Questions