A
A
Alexey Semenov2018-12-17 13:06:18
C++ / C#
Alexey Semenov, 2018-12-17 13:06:18

How to collapse data in C# using Linq?

There is a Json - in which something like this comes in

{
  'orders' : [ 
    {
      id: 1,
      sku: 'AR',
      sum: 100
    },
    {
      id: 2,
      sku: 'PR',
      sum: 200
    },
    { 
      id: 1,
      sku: 'VR',
      sum: 150
    },
  ]
}

if the id's are the same, sum should be summed, and sku should be in the form of an array

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
devilya, 2018-12-17
@aleksey_semenov

It is not very clear what kind of array you want to get, but if, by analogy with summation, string concatenation is performed, then, for example, like this:

class Program
    {
        static void Main(string[] args)
        {
            List<Order> orders = new List<Order>()
            {
                new Order()
                {
                    id = 1,
                    sku = "AR",
                    sum = 100
                },
                new Order()
                {
                    id = 2,
                    sku = "PR",
                    sum = 200
                },
                new Order()
                {
                    id = 1,
                    sku = "VR",
                    sum = 150
                }
            };

            var groupedOrders = orders.GroupBy(el => el.id)
                .Select(el => new Order()
                {
                    id = el.Key,
                    sum = el.Sum(s => s.sum),
                    sku = String.Join(String.Empty, el.Select(str => str.sku))
                });
           
        }
    }

    public class Order
    {
        public int id;
        public string sku;
        public int sum;
    }

L
LiptonOlolo, 2018-12-17
@LiptonOlolo

It is not clear what the array should be for the Sku field, but without it it will look something like this:

class Program
{
  static void Main(string[] args)
  {
    string rawJson = File.ReadAllText("data.json"); // for example
    OrderCollection orders = JsonConvert.DeserializeObject<OrderCollection>(rawJson);

    foreach (var item in orders.Orders.GroupBy(x => x.Id))
    {
      Console.WriteLine($"Order id: {item.Key}, sum: {item.Sum(x => x.Sum)}");
    }
  }
}

class OrderCollection
{
  public List<Order> Orders { get; set; }
}

class Order
{
  public int Id { get; set; }
  public string Sku { get; set; }
  public int Sum { get; set; }
}

5c178d80a1678903608751.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question