Programming Newbie Programming Newbie - 3 months ago 10
C# Question

How to change multiple foreach iteration to single LINQ?

emailAddresses
is the List of strings.
notificationRequest
is the class has the field
RequestXml
(type is
XDocument
).

RequestXml
will be like:

<root>
<result>
<SUBMITTERALIAS>example@domain.com</SUBMITTERALIAS>
</result>
<result>
<SUBMITTERALIAS>example@domain.com</SUBMITTERALIAS>
</result>
</root>


I want to get all the email address in the
SUBMITTERALIAS
to be saved in the string list. So I wrote the following piece of code. I did work and does the job.

var emailAddresses = new List<string>();

foreach (var request in notificationRequest)
{
foreach (var email in request.RequestXml.Descendants("SUBMITTERALIAS"))
{
emailAddresses.Add(email.Value);
}
}


I would like to use single line LINQ code instead of above foreach. Any ideas?

Answer

If you want to add the address to another list you can flatten the lists with SelectMany and use AddRange:

emailAddresses.AddRange(notificationRequest.SelectMany(request =>
                  request.RequestXml.Descendants("SUBMITTERALIAS"))
                  .Select(email => email.Value));

If you create a complete new list you can simply call it like that:

emailAddresses = notificationRequest.SelectMany(request =>
                  request.RequestXml.Descendants("SUBMITTERALIAS"))
                  .Select(email => email.Value).ToList();