1

I have the following:

foreach (var objectiveDetail in add)
{
    _uow.ObjectiveDetails.Add(objectiveDetail);
}

Is there a way I could do this in LINQ.

  • 3
    Is there any particular reason or it's just because "I can"? To me it's perfectly valid and even more readable your current approach... –  Jan 22 '14 at 04:34

4 Answers4

5

Or just:

_uow.ObjectiveDetails.AddRange(add);
Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
  • +1 My personal favorite.. Assuming _uow.ObjectiveDetails is a type that supports `AddRange(IEnumerable)`. – Nico Jan 22 '14 at 04:34
  • If not.. LINQ's `Concat` is the same. – Simon Whitehead Jan 22 '14 at 04:36
  • If I could +2 this I would.. The add range uses the `Array.Copy` and 'Array.CopyTo' methods which do not enumerate the set if the added collection implements `ICollection`. Although marginal will execute quicker and cleaner. – Nico Jan 22 '14 at 04:39
1
add.Foreach(o => _uow.ObjectiveDetails.Add(o));

Try the above

Here is another answer/question ToList().ForEach in Linq

Community
  • 1
  • 1
TGH
  • 38,769
  • 12
  • 102
  • 135
  • I think I recommend using your original approach though. It's more readable IMO – TGH Jan 22 '14 at 04:35
1

You mean something like this?

add.ForEach( (objectiveDetail) => _uow.ObjectiveDetails.Add(objectiveDetail));

By the way this is not LINQ.This is just a method of generic List<T> class.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • Thanks. I will accept your answer as I believe it was the first correct answer. –  Jan 22 '14 at 04:33
  • 1
    This isn't strictly correct. Only `List` natively supports this method. You need to include a reference to the Interactive Framework (by the Reactive Framework guys) to get this on `IEnumerable`. – Enigmativity Jan 22 '14 at 04:35
  • 1
    @Enigmativity, I mention it just now :) – Selman Genç Jan 22 '14 at 04:36
0

You could do this in a foreach if add is a List<T> by calling the method ForEach(Action<T> action)

Such as.

add.ForEach(item => _uow.ObjectiveDetails.Add(item));

Nico
  • 12,493
  • 5
  • 42
  • 62