I’m new to lambda expressions and looking to leverage the syntax to set the value of one property in a collection based on another value in a collection
Typically I would do a loop:
class Item
{
public string Name { get; set; }
public string Value { get; set; }
}
void Run()
{
Item item1 = new Item { Name = "name1" };
Item item2 = new Item { Name = "name2" };
Item item3 = new Item { Name = "name3" };
Collection<Item> items = new Collection<Item>() { item1, item2, item3 };
// This is what I want to simplify.
for (int i = 0; i < items.Count; i++)
{
if (items[i].Name == "name2")
{
// Set the value.
items[i].Value = "value2";
}
}
}
LINQ is generally more useful for selecting data than for modifying data. However, you could write something like this:
This first selects items that need to be modified and then modifies all of them using a standard imperative loop. You can replace the
foreachloop withForAllmethod that’s available for lists, but I don’t think this gives you any advantage:Note that you need to add
ToListin the middle, becauseForEachis a .NET 2.0 feature that’s available only forList<T>type – not for allIEnumerable<T>types (as other LINQ methods). If you like this approach, you can implementForEachforIEnuerable<T>:Anyway, I’d prefer
foreachloop, because that also makes it clear that you’re doing some mutation – and it is useful to see this fact easily in the code.