How to GROUP BY using Iteration?

Viewed 94

I'm trying to GROUP the JSON by BOARD and SUM the likes_count, but not sure how to approach this, since I can only access the Transaction class by looping through Root first?

    public class Transaction
{
    public string Post { get; set; }
    public int board {get; set; }
    public int Sent_from { get; set; }
    public int likes_count { get; set; }
}

public class Root
{
    public int Sent_to { get; set; }
    public List<Transaction> Transactions { get; set; }

}

static async System.Threading.Tasks.Task Main(string[] args)
{


    var json = "";      
    using (WebClient wc = new WebClient())
    {
        json = wc.DownloadString("xxxxxxx");
    }
    var obj = JsonConvert.DeserializeObject<List<Root>>(json);

    foreach (var item in obj)
    {

        foreach (var child in item.Transactions)
        {
            
            // access sent_from, likes_count and post.

        }

    }
}

I would've normally used:

obj.GroupBy(t => t.post);

Here is a JSON Sample:

Sent_to: X,
total_received_likes: X,
Transactions: [
{
Post: "50776785",
board: "600",
Sent_from: 359716,
likes_count: 4,
},
{
Post: "5085129785",
board: "500",
Sent_from: 359716,
likes_count: 6,
},
{

Post: "506542785",
board: "500",
Sent_from: 359716,
likes_count: 9,
},

The expected output in this case:

15 likes in board 500

4 likes in board 600.

1 Answers

If you want to group the Transactions by board regardless of which Root they belong to and then calculate the sum of likes_count for each group, you may create a list using something like this:

var list = obj.SelectMany(r => r.Transactions)
              .GroupBy(t => t.board)
              .Select(g => new { Board = g.Key, TotalLikes = g.Sum(t => t.likes_count) })
              .ToList();

..which you can then use like this:

foreach (var item in list)
{
    Console.WriteLine($"{item.TotalLikes} like(s) in board {item.Board}.");
}

You can also do the same thing for each Root separately if you like:

foreach (var root in obj)
{
    var list = root.Transactions
                   .GroupBy(t => t.board)
                   .Select(g => new { Board = g.Key, TotalLikes = g.Sum(t => t.likes_count) })
                   .ToList();
}
Related