在实现这一点时遇到一些麻烦,我有一个我在LINQ中按帐户分组的事务列表,现在它给了我一个可以计算所有帐户的数量,每个帐户都有一个可枚举的事务。我现在想要获取该列表,并按每个组的事务总和进行排序,但它似乎不起作用,这是我到目前为止所做的:
var memberTrans = trans.GroupBy(o => o.ShareAccountId);
var transOrdered = memberTrans.OrderByDescending(o => o.Sum(i => i.TransactionAmount));
这个想法是,我可以做.First()并获得期间净增长最高的账户,而.Last()则获得净增长最低的账户。
假设我有以下数据(简化)
所以第一个分组给了我:
帐户1:
帐户2:
帐户3:
现在我想通过每个组内交易的SUM来订购它,所以我们有这个清单:
帐户2:
帐户3:
帐户1:
希望这很清楚,任何帮助都非常感谢!
编辑:更清晰的代码:
var tranOrder = trans.GroupBy(o => o.ShareAccountId).OrderByDescending(g => g.Sum(t => t.TransactionAmount));
var bigUp = tranOrder.First().First();
var bigDown = tranOrder.Last().First();
report.BiggestMovementUp = tranOrder.First().Sum(o => o.TransactionAmount);
report.BiggestMoverUp =
(bigUp.Member.Title + " " + bigUp.Member.Forename + " " + bigUp.Member.Surname + " - ID " + bigUp.Member.MemberID).Trim();
report.BiggestMovementDown = tranOrder.Last().Sum(o => o.TransactionAmount);
report.BiggestMoverDown =
(bigDown.Member.Title + " " + bigDown.Member.Forename + " " + bigDown.Member.Surname + " - ID " + bigDown.Member.MemberID).Trim();
var bigUp = tranOrder.First().First();
var bigDown = tranOrder.Last().First();
report.BiggestMovementUp = tranOrder.First().Sum(o => o.TransactionAmount);
report.BiggestMoverUp =
(bigUp.Member.Title + " " + bigUp.Member.Forename + " " + bigUp.Member.Surname + " - ID " + bigUp.Member.MemberID).Trim();
report.BiggestMovementDown = tranOrder.Last().Sum(o => o.TransactionAmount);
report.BiggestMoverDown =
(bigDown.Member.Title + " " + bigDown.Member.Forename + " " + bigDown.Member.Surname + " - ID " + bigDown.Member.MemberID).Trim();
答案 0 :(得分:1)
var v = (from acc in accs
group acc by acc.ShareAccountId into g
orderby g.Sum(x => x.TransactionAmount) descending
select g.Sum(x => x.TransactionAmount));
应该这样做,你可以在选择中做任何你想做的事。我也测试了这个。
答案 1 :(得分:0)
这个怎么样:
internal class Program
{
private class AccountOperation
{
public int Id { get; set; }
public int Amount { get; set; }
}
private static void Main(string[] args)
{
List<AccountOperation> ops = new List<AccountOperation>
{
new AccountOperation { Id = 1, Amount = 300},
new AccountOperation { Id = 1, Amount = -300},
new AccountOperation { Id = 2, Amount = 100},
new AccountOperation { Id = 3, Amount = 50},
new AccountOperation { Id = 2, Amount = -20},
};
foreach (var operationsByAccount in ops
.OrderByDescending(z => z.Amount) // Orders all amounts descending
.GroupBy(z => z.Id) // Groups by account ID
.OrderByDescending(z => z.Sum(z2 => z2.Amount))) // Orders groups of operations per accounts descending (by sum of amounts)
{
Console.WriteLine("Operation " + operationsByAccount.Key);
foreach (var operation in operationsByAccount)
{
Console.WriteLine("\tAmout " + operation.Amount);
}
}
Console.ReadLine();
}
}
输出:
答案 2 :(得分:0)
修复方法链接版本:
var v = accs.GroupBy(acc => acc.ShareAccountId)
.OrderByDescending(g => g.Sum(x => x.TransactionAmount))
.Select( g => g.Sum(x => x.TransactionAmount));
不可否认,我让Resharper从LINQ语法中为我做这个:)