user5534263
user5534263

Reputation: 148

converting foreach to LINQ while writing to Logger or Console

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);
} 

Upvotes: 1

Views: 638

Answers (3)

Jiri Sykora
Jiri Sykora

Reputation: 486

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.

Upvotes: 0

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43896

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.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

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);
);

Upvotes: 3

Related Questions