1

I have the following list:

    public class Prices
    {
        public int Year { get; set; }
        public decimal Price { get; set; }
    }

    List<Prices> List1 = new List<Prices>();
    List1.Add(new Prices { Year = 2018, Price = 1.5m });
    List1.Add(new Prices { Year = 2017, Price = 1.2m });
    List1.Add(new Prices { Year = 2016, Price = 3.5m });

    //The linq query i'm trying to build
     var data1 = List1.Select(c=> new
         {
             labels = new List<Int64> {c.Year },
             series = new List<decimal> {
                 new List<decimal> { c.Price }
             }
         });


    // it's what i want to build
    var data2 = new {
      labels = new List<Int64> { 2018, 2017, 2016 },
      series = new List<decimal[]> {
               new decimal[] { 1.5m, 1.2m, 3.5m }
        }
    };

    var Json = JsonConvert.SerializeObject(data2);
    //Json => {"labels":[2018,2017,2016],"series":[[1.5,1.2,3.5]]}

I wish to convert the List1 to a Json Output using linq:

{"labels":[2018,2017,2016],"series":[[1.5,1.2,3.5]]}

2 Answers 2

4

Create a new object containing properties for labels and prices where each is populated using a .Select() to select the appropriate values.

var data = new
{
    labels = List1.Select(x => x.Year),
    prices = new []{ List1.Select(x => x.Price) }
};
var Json = JsonConvert.SerializeObject(data);
Sign up to request clarification or add additional context in comments.

Comments

0

Expanding on user3559349's answer, put it in a class or view model...

Public class ChartModel
{
    public ChartUnit[] Chart { get; set; } = Array.Empty<ChartUnit>();

    public string ToJson()
    {
        var data = new
        {
            lables = Chart.Select(s => s.Label),
            Value = Chart.Select(s => s.Value)
        };

        var json = JsonConvert.SerializeObject(data);
        return json;
    }
}

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.