4

I have an object structure that looks like this:

var Results = new List<ResultObj>()
    {
        new ResultObj()
        {
            Messages = new List<MessageObj>()
            {
                new MessageObj()
                {
                    Message = "message 1"
                },
                new MessageObj()
                {
                    Message = "message 2"
                }
            }
        },
        new ResultObj()
        {
            Messages = new List<MessageObj>()
            {
                new MessageObj()
                {
                    Message = "message 3"
                }
            }
        }
    }

How do I use LINQ or another C# approach to get a single string with all the Message values concatenated together? Something like what's below

"message 1, message 2, message 3"

Thanks!

3 Answers 3

5

Use String.Join and SelectMany:

String.Join(", ", Results.SelectMany(x=> x.Messages).Select(y => y.Message ));
Sign up to request clarification or add additional context in comments.

1 Comment

The use of SelectMany(x => x) will select the ResultObj items, not the Messages that belong to each ResultObj.
5

Use the Enumerable.SelectMany method to flatten the list, then use the String.Join method.

var query = Results.SelectMany(r => r.Messages)
                   .Select(m => m.Message);
var result = String.Join(", ", query);

Comments

1
var allStrings = results.SelectMany(r => r.Messages).Select(m => m.Message);
var joined = String.Join(", ", allStrings);

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.