1

Given the following piece of foreach code how do I write it as a LINQ

foreach(var error in ex.Errors)
{
   Logger.Error("Field {0} has an error : {1}. for SSN {2}",error.FieldName,    error.Message, error.SSN);
} 
6
  • 5
    Why do you want to write it in LINQ? Commented Jan 25, 2016 at 16:31
  • 6
    No need for LINQ here Commented Jan 25, 2016 at 16:32
  • Linq isn't for side effects. That's what loops are for which you already have. Commented Jan 25, 2016 at 16:33
  • wondering if it was worth it to write as LINQ. From the comments I see its not. Commented Jan 25, 2016 at 16:36
  • if you really want to avoid using foreach here, you could use the List<T>.ForEach(Action<T>) to do the same, it is more obscure though Commented Jan 25, 2016 at 16:37

3 Answers 3

3

LINQ is for producing results, such as new sequences and aggregates. It is not a good fit for producing side effects, such as log outputs.

The foreach loop in your code is a perfectly acceptable, very readable solution. If you would like to get rid of it anyway, you could use List.ForEach method, which takes an Action<T>:

ex.Errors.ForEach(
    error => Logger.Error(
        "Field {0} has an error : {1}. for SSN {2}"
    ,   error.FieldName
    ,    error.Message
    ,   error.SSN);
);
Sign up to request clarification or add additional context in comments.

1 Comment

not always as clear as using a dedicated foreach loop, but I have used this before myself.
0

I personally would not do this, but if you really want to use LINQ here, there are two options:

ex.Errors.ForEach(error => Logger.Error("Field {0} has an error : {1}. for SSN {2}", error.FieldName, error.Message, error.SSN));

or

Logger.Error(string.Join(Environment.NewLine, 
    ex.Errors.Select(error => 
        string.Format("Field {0} has an error : {1}. for SSN {2}", error.FieldName, error.Message, error.SSN))));

But the second one depends a little on how your Logger.Error is implemented and if it's ok to join the strings.

Comments

0

You can convert to list and use ForEach

ex.Errors.ToList().ForEach(error =>
{
    Logger.Error("Field {0} has an error : {1}. for SSN {2}", error.FieldName, error.Message, error.SSN);
});

Alternatively, write your own ForEach extension method:

public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
    foreach(T item in enumeration)
    {
        action(item);
    }
}

But in this case is probably better don't using Linq.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.