Using LINQ to Update A Property in a List of Entities

Viewed 116354

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.

5 Answers

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();

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()
Related