[英]How to Do GroupBy with List<List<int>> and Return List<List<int>> in C#?
這是我問的上一個問題( 如何在循環中將 JSON 元素分配給 2D 數組)的后續問題。 我的數據從一個 JSON 對象開始:
JSON
{"page":"1",
"per_page":10,
"total":100,
"total_pages":10,
"data":[{"id":1,
"userId":1,
"userName":"Jim Silver",
"timestamp":16425382171,
"txnType":"debit",
"amount":"$1,000.07",
"location":{"id":2,
"address":"654, Somewhere, Some Street",
"city":"Some City",
"zipCode":12345},
"ip":"202.210.105.105"},
{"id":2," ...}
{"id":3," ...}
...
{"id":n," ...}]
我需要將用戶 ID 和金額放入我在這里完成的List<List<int>>
中:
var model = JsonConvert.DeserializeObject<TxnResponse>(rawJSON);
var elements = model.data;
List<List<int>> userTxns = new List<List<int>>(elements.Count);
List<int> record = null;
int userID = 0;
int userAmount = 0;
for (int row = 0; row < elements.Count; row++)
{
userID = elements[row].userId;
userAmount = Convert.ToInt32(Math.Floor(decimal.Parse(model.data[row].amount, System.Globalization.NumberStyles.Currency)));
record = new List<int>();
record.Add(userID);
record.Add(userAmount);
userTxns.Add(record);
}
return userTxns.GroupBy();
打印到屏幕時,結果應如下所示( Console.WriteLine(String.Join("\\n", list.Select(x => String.Join(" ", x))));
): 1 1000 2 2000 3 3000 4 4000
如果沒有 Group By,如果 JSON 對象有 10 個數據項,我就有 10 個用戶 ID、金額記錄。 我試過return userTxns.GroupBy(userID);
並return userTxns.GroupBy(u => userID);
但得到“無法從用法推斷出方法的類型參數......”或“無法隱式轉換類型......”。
模型:
public class TxnResponse
{
public string page { get; set; }
public int per_page { get; set; }
public int total { get; set; }
public int total_pages { get; set; }
public List<data> data { get; set; }
}
public class data
{
public int id { get; set; }
public int userId { get; set; }
public string userName { get; set; }
public object timestamp { get; set; }
public string txnType { get; set; }
public string amount { get; set; }
public Location location { get; set; }
public string ip { get; set; }
}
public class Location
{
public int LocationID { get; set; }
public string Address { get; set; }
public string City { get; set; }
public int ZipCode { get; set; }
}
如何對用戶 ID 進行 GroupBy? 謝謝你。
這工作...
return userTxns.GroupBy(u => u[0], (key, values) => new List<int>
{
key,
values.Select(l => l[1]).Sum()
}).OrderBy(u => u[0]).ToList();
但是有 16 頁數據,我的 REST 調用只返回第一頁......我會發布一個后續問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.