Get Off My Lawn Get Off My Lawn - 10 days ago 6
C# Question

Apply a callback to a list of items with LINQ

I am trying to modify the items in a list based on whether or not they match a LINQ Where query.

I tried doing it this way:

class Collection<T> {

public List<T> Items { get; private set; }

public Collection<T> Modify(Func<T, bool> query, Func<T, T> callback) {
Items = Items.Where(query).Select(callback).ToList();
return this;
}
}


But this removes items from the list if it doesn't match. I would like to just skip over the item, and leave it in the list. How can I accomplish this?

Answer

I think you could do this:

 Items= Items.Select(e=>query(e)?callback(e):e).ToList();