0

What's the best approach to this situation:

I have a large list that contains a DateTime property in each object and I need to add the offset and modify the date manually. I wish I can do it in LINQ like so:

select new VM { DateTime = history.DateTime == null ? null : history.DateTime.AddHours(offset) }

My only option is to loop through? I'm not the one that adds the data to the db so I can't add the offset on insert.

GH DevOps
  • 305
  • 1
  • 11
  • Does this answer your question? [LINQ equivalent of foreach for IEnumerable](https://stackoverflow.com/questions/200574/linq-equivalent-of-foreach-for-ienumerablet) – 41686d6564 stands w. Palestine Aug 26 '21 at 19:03
  • I know how to do a foreach. I'm trying to avoid that. – GH DevOps Aug 26 '21 at 19:07
  • If I understand correctly, you're asking for a LINQ alternative of a foreach loop, right? If not, you might want to [edit] the question to clarify. – 41686d6564 stands w. Palestine Aug 26 '21 at 19:08
  • How are you planning to go through all items without looping through them? One thing you could optimize is the null check within the statement... just store `var actualDt = history.Datetime?.AddHours(offset)` outside the linq and use it within the loop: you'll avoid a nullability check on each loop – Jcl Aug 26 '21 at 19:28
  • I wanted to add the hours in my LINQ query when I populated the list – GH DevOps Aug 26 '21 at 19:32
  • @GHDevOps you can do it as you are doing there, however you'll need to populate the whole `VM` object, not just the property you want to change – Jcl Aug 26 '21 at 19:35
  • LINQ doesn't seem to like the .AddHours() extension method – GH DevOps Aug 26 '21 at 19:51

1 Answers1

1

Why are you trying to avoid foreach and List<T>.ForEach?

You can do it with LINQ, but it still loops under the hood:

list.Select(obj => obj.DateTime = obj.DateTime?.AddHours(offset)).ToList(); // Discard the result
Spencer Bench
  • 647
  • 4
  • 7