Daniel Hollinrake
Daniel Hollinrake

Reputation: 1778

Is it possible to use Linq to replace this Foreach loop

Is it possible to replace the foreach statement with a Linq command?

            string recipient = "recipients could not be defined"; 
            if (mail.To != null && mail.To.Count > 0) {
                var addresses = mail.To.Select(r => r.Address);
                foreach (string s in addresses) {
                    recipient += s + " ";
                }
            }

If I had ReSharper then I'm sure it would have come up with an appropriate suggestion but I don't. This question uses Concat and that feels like it should help but I'm not certain as to what object to use in the Concat.

Upvotes: 1

Views: 191

Answers (1)

Matthew Steeples
Matthew Steeples

Reputation: 8073

Rather than using the Linq foreach (which is only available on List<T> unless you've written your own), you can do it backwards and avoid the string concatenation in the process:

recipient = string.Join(" ", mail.To.Select(r => r.Address));

This replaces your var addresses... onwards.

Upvotes: 9

Related Questions