Search code examples
c#linqlinq-to-objects

How to modify IEnumerable with LINQ to avoid foreach loop?


Can the following be done in LINQ as a one-liner, without using a for-loop?

IEnumerable<MyObj> MyList = EF.GetList(etc);
foreach (var row in MyList)
{
    row.uploadedAt = MyUtils.ConvertToLocalTime(row.uploadedAtUTC, clientTimezone);
}
//return MyList, which now has both dates in LocalTime and UTC

Solution

  • Reassign the list, ideally without mutating anything. This would be more consistent with the functional programming mindset of LINQ.

    IEnumerable<MyObj> myList1 = EF.GetList(etc);
    IEnumerable<MyObj> myList2 = myList1.Select( x => 
            new MyObj 
            {
                uploadedAt = MyUtils.ConvertToLocalTime(x.uploadedAtUTC, x.clientTimezone),
                anyOtherFields = x.anyOtherFields
            }
        ).ToList();
    

    If constructing a MyObj is complicated and/or you really need to mutate it, you can also do this:

    IEnumerable<MyObj> myList = EF.GetList(etc);
    myList = myList.Select( x => {
            x.uploadedAt = MyUtils.ConvertToLocalTime(x.uploadedAtUTC, x.clientTimezone);
            return x;
        }).ToList();
    

    But if you're going to do it that way, you may as well use the for loop.