How to Update Members of a Collection with LINQ -- Visual Studio Magazine


Mon Jul 04 2022 19:42:53 GMT+0000 (UTC)

Saved by @dhfinch #c# #linq #lambda #extensionmethod

public static class PHVExtensions
    public static IEnumerable<T> SetValue<T>(this IEnumerable<T> items, Action<T>
        foreach (T item in items)
        return items;

With that method in place, I can write my statement like this:
customers.Where(c => c.IsValid).SetValue(c => c.CreditLimit = 1000).ToList();

Or like this:
var newCustomers = customers.Where(c => c.IsValid).SetValue(c => c.CreditLimit = 1000);

Or like this for Entity Framework:
db.Customers.Where(c => c.IsValid).ToList().SetValue(c => c.CreditLimit = 1000);

I can write an extension method of my own that will attach itself to any collection that implements the IEnumerable interface. My extension method will, in turn, accept a lambda expression that accepts an object out of the collection. Within my extension method, I can loop through the collection my method has been called from. Within that loop, I'll call the lambda expression that's been passed in to my method, passing the lambda expression each object from the collection. Finally, I can return the updated collection: