2

我正在尝试通过 BOARD 对 JSON 进行分组,并对 likes_count 求和,但不知道如何解决这个问题,因为我只能通过首先循环访问 Root 来访问 Transaction 类?

    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.

        }

    }
}

我通常会使用:

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

这是一个 JSON 示例:

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,
},

在这种情况下的预期输出:

板 500 中有 15 个赞

4 个赞在板 600 中。

4

1 回答 1

3

如果您想对事务进行分组,board而不管Root它们属于哪个事务,然后计算likes_count每个组的总和,您可以使用以下内容创建一个列表:

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();

..然后您可以像这样使用它:

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

如果您愿意,也可以分别为每个执行相同的操作Root

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();
}
于 2020-06-28T10:42:22.033 回答