C# List - Group By - Without Linq

后端 未结 2 1712
眼角桃花
眼角桃花 2020-12-22 01:30

I have an object:

IObject
{
    string Account,
    decimal Amount
}

How do I group by Account and Sum the Amount, returning a List without

2条回答
  •  难免孤独
    2020-12-22 01:48

    Use a dictionary to hold the results. Locating an item in a dictionary is close to an O(1) operation, so it's a lot faster than searching for items in a list.

    Dictionary sum = new Dictionary();
    
    foreach (IObject obj in objects) {
       if (sum.ContainsKey(obj.Account)) {
          sum[obj.Account].Amount += obj.Amount;
       } else {
          sum.Add(obj.Account, obj.Amount);
       }
    }
    

提交回复
热议问题