Issue
I’m try to pass an entity to a method by parameter, but I don’t want to do a for or foreach. How can I pass this parameter without using for or foreach with a lambda expression?
This is my code:
private async Task SaveParents()
{
try
{
await Task.Run(() => {
List<Parent> parents = new List<Parent>();
parents.AddRange(GetParents();
parents.AddRange(GetParentsTwo();
_iData.SaveParents(parents); //Here I want to pass each of the elements with lambda
});
}
}
Thank you 😀
Solution
Out of the box, LINQ doesn’t support what you are trying to do.
If you’re really adamant about this, though, it’s a trivial matter to write an extension method that will do this for you:
public static class LinqExtensions
{
public static void ForEach(this IEnumerable<T> sequence,
Action<T> action)
{
forEach(var item in sequence)
{
action(item);
}
}
}
Then in your code sample (note I had to change the method signature to take a single item):
private async Task SaveParents()
{
try
{
await Task.Run(() => {
List<Parent> parents = new List<Parent>();
parents.AddRange(GetParents();
parents.AddRange(GetParentsTwo();
parents.ForEach(p => _iData.SaveParent);
});
}
}
Note that just because you can do this does not necessarily mean you should. Microsoft’s argument against including IEnumerable<T>.ForEach
is that queries should not have side-effects. That’s a fairly compelling argument.
Answered By – Mike Hofer
Answer Checked By – Clifford M. (BugsFixing Volunteer)