Reputation: 5119
I didn't know how to phrase the title of this post. This is what I am trying to do:
invalidItems.AddRange(documents.SelectMany(doc => doc.Messages)
.Select(message => string.Format("Doc. Key {0}: {1}", doc.ID, message)));
Where invalidItems is a List and Document is a class that contains a List property called messages.
I want to get a flat list of the messages (strings) for all of the documents, where the strings are formatted to include the Document ID (similar to the String.Format() above). Is there a way to accomplish this?
When I working with the message parameter in the final .Select() clause, I am unable to access anything on the parent Document...
Upvotes: 2
Views: 449
Reputation: 110111
If you want more scope in your queries, query comprehension syntax may be the way to go.
from doc in documents
from message in doc.Messages
select string.Format("Doc. Key {0}: {1}", doc.ID, message)
which is equivalent to:
documents
.SelectMany(
doc => doc.Messages,
(doc, message) => new {doc, message}
)
.Select(
x => string.Format("Doc. Key {0}: {1}", x.doc.ID, x.message)
)
Upvotes: 0
Reputation: 39610
You just need to move the select clause into your SelectMany clause like this:
documents.SelectMany(
doc => doc.Messages.Select(
message => string.Format("Doc. Key {0}: {1}", doc.ID, message)
)
);
Upvotes: 1