Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating strings in C# object structure

Tags:

c#

linq

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!

like image 519
swingdoctor Avatar asked Dec 21 '22 05:12

swingdoctor


1 Answers

Use String.Join and SelectMany:

String.Join(", ", Results.SelectMany(x=> x.Messages).Select(y => y.Message ));
like image 161
Aliostad Avatar answered Jan 04 '23 23:01

Aliostad