Concatenating strings in a C # object structure

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 to use LINQ or another C # approach to get one row with all Message values ​​concatenated together? Something like the one below

"message 1, message 2, message 3"

Thanks!

+4
source share
3 answers

Use String.Join and SelectMany :

 String.Join(", ", Results.SelectMany(x=> x.Messages).Select(y => y.Message )); 
+5
source

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

 var query = Results.SelectMany(r => r.Messages) .Select(m => m.Message); var result = String.Join(", ", query); 
+5
source
 var allStrings = results.SelectMany(r => r.Messages).Select(m => m.Message); var joined = String.Join(", ", allStrings); 
+1
source

Source: https://habr.com/ru/post/1382698/


All Articles