Answer the question
In order to leave comments, you need to log in
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
},
]
}
Answer the question
In order to leave comments, you need to log in
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;
}
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; }
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question