Search code examples
c#linqodata

How to GroupBy when retrieving data from OData API?


I am retrieving data from OData API and projecting it into a different class:

            data = context.Product.Where(p => p.name == name)
                                             .Take(10)
                                             .Select(p => new MyCustomProduct
                                             {
                                                 id = p.id,                                                 
                                                 year = p.year,
                                                 amount = p.amount,                                                 
                                                 customProperty = 00
                                             });

This works fine. However, I also need a function to group the retrieved products by year, and calculate the total amount of products for each year. How is it possible to achieve that?


Solution

  • First group your result by year, then calc the sum for each year:

    var data = context.Product.Where(p => p.name == name)
                          .Take(10)
                          .GroupBy(p => p.year)
                          .Select(group => new { year = group.Key, sum = group.Sum(p => p.amount) })
                          .ToList();
    

    your data variable then is List<a'> where a' = { int year, int sum }