Parse JSON string within the JSONResults using C# LINQ

TheCoder 91 Reputation points
2023-02-14T17:12:46.0166667+00:00

This is the first time I've ran into this.

I have data stored in the table such as:

;kenworth;peterbilt;volvo

I have an LINQ statement such as

public Task<JsonResult> GetTruckMakes()
{
    var results = _context.Details
      .Select (x => new 
       {
            id = x.TruckId,
            model = x.Models
            makes = x.Makes  // this is where the data is returned as ;kenworth;peterbilt;volvo
       });
   
      return new JsonResult(results.ToListAsync());

this is how the data is returned:

is there a way to get all of the makes per id separated, they'll be populated a textbox on the screen



Developer technologies .NET Entity Framework Core
Developer technologies C#
{count} votes

1 answer

Sort by: Most helpful
  1. Alan Farias 755 Reputation points
    2023-02-24T15:18:18.6333333+00:00

    You didn't post the return, but I guess you could split the string of makes by the semicolon character ';' using the Split() method, and return an array of individual makes for each record.

    Here's an example:

    public Task<JsonResult> GetTruckMakes()
    {
        var results = _context.Details
            .Select(x => new
            {
                id = x.TruckId,
                model = x.Models,
                makes = x.Makes.Split(';') // Split the makes string into an array of individual makes
            });
    
        return new JsonResult(await results.ToListAsync());
    }
    
    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.