0

I have a Web API which returns following data:

{   
     "code": "Invalid",
     "message": "The following fields are invalid",
     "details": [
        {
             "property": "User",
             "messages": [
                 "FirstName is required",
                 "LastName is required",
             ]
        },
        {
             "property": "User.Gender",
             "messages": [
                 "Incorrect or Invalid"
             ]
        },
        {
             "property": "MarialStatus",
             "messages": [
                 "Cannot be validated"                 
              ]
        },
        {
             "property": "EmployeeId",
             "messages": [
                 "User's employeeId is required"
             ]
        },
}

This is my model object:

public class WebApiResponse
{
     public string code { get; set; }
     public string message { get; set; }
     public List<Details> details { get; set; }
}

public class Details
{
     public string property{ get; set; }
     public List<string> messages { get; set; }
}

I want to display the "messages" only for the selected "property" into a single string separated by a new line, so I can add the string to a DataTable row.

For eg: I tried this to get the list of "messages"

var data = WebApiResponse.details.Where(x => x.property == "User" || x.property == "EmployeeId").Select(x => x.messages);

How do I convert this list so I can get the "messages" in a single string separated by new line:

 FirstName is required
 LastName is required
 User's employeeId is required
DevP
  • 75
  • 2
  • 11

1 Answers1

1

Use SelectMany instead of Select to flatten the nested list, then String.Join to join the strings :

var targets = new[]{"User", "EmployeeId"];
var messages = WebApiResponse.details
                             .Where(x => targets.Contains(x.property))
                             .SelectMany(x => x.messages);

var line = string.Join(Environment.NewLine, messages);
Pavel Tupitsyn
  • 8,393
  • 3
  • 22
  • 44
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236