Manipulating Objects in a Collection with LINQ

I was chatting with a co-worker about using LINQ to replace for-each loops. More specifically, we were discussing how to modify the properties of items in a collection or a subset of the collection. I didn’t know how to do it immediately, but I worked on it a bit and found a pretty cool way to do just that.

My first thought was that you could just put your logic into a Select method, modify the objects, and then return a dummy value that would be ignored. Something like this:

// this does not work!
values.Select(x =>
    x.Name = x.Name.ToUpper();
    return true;

This did not work, though! I’m not entirely sure why, but I tried a few different approaches and found a way that does work. It feels less hacky, too, since I’m not returning that meaningless dummy value.

Here’s the solution that I came up with:

values.Aggregate(null as Person, (av, e) =>
    e.Name = e.Name.ToUpper();
    return av ?? e;

If you only want to manipulate a subset of the collection, you can insert a Where method before your aggregate, like this:

values.Where(x => x.Name.Equals("Blah"))
    .Aggregate(null as Person, (av, e) =>
        e.Name = e.Name.ToUpper();
        return av ?? e;

You can read more about the Aggregate method here.


Author: Adam Prescott

I'm enthusiastic and passionate about creating intuitive, great-looking software. I strive to find the simplest solutions to complex problems, and I embrace agile principles and test-driven development.

Leave a comment

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: