Linq循环通过子集合和总收入

时间:2017-02-21 13:15:32

标签: c# asp.net linq c#-4.0 sum

我的结构如下:

class Items
{
//item properties
List<Transactions> _ItemTransactions {get;set;}
}

transaction类包含以下元素:

class Transactions
{
public int QuantitySoldTotal {get;set;}
public double TransactionPrice {get;set;}
}

我试图将所有物品交易的所有重新加起来。我试图做这样的事情:

  var totalRevenue = Context.Items.AsParallel().Select(x => x._ItemTransactions.Sum(y => y.TransactionPrice * y.QuantitySoldTransaction)).FirstOrDefault();

但我总是得到0值作为回报......有人可以帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:2)

Linq有Sum方法

double totalRevenue = items._ItemTransactions.Sum(transaction => transaction.TransactionPrice * transaction.QuantitySoldTotal);

要总结列表,您可以执行类似

的操作
double totalRevenue = Context.Items.Sum(items => items._ItemTransactions.Sum(transaction => transaction.TransactionPrice * transaction.QuantitySoldTotal));

或者

double totalRevenue = Context.Items.SelectMany(items => items._ItemTransactions).Sum(transaction => transaction.QuantitySoldTotal * transaction.TransactionPrice);

答案 1 :(得分:1)

var totalRevenue = Context.Items.AsParallel().Select(x => x.Transactions.Sum(y => y.TransactionPrice * y.QuantitySoldTransaction)).FirstOrDefault();

让我们分解你在这里做的事情

Context.Items.AsParallel()并行运行(可能不需要)返回IEnumerable<Item>

列表中每个项目的

.Select(x => x.Transactions.Sum(y => y.TransactionPrice * y.QuantitySoldTransaction))总结了交易,从而为您留下IEnumerable<double>

.FirstOrDefault();获取IEnumerable<double>结果中的第一项,在您的情况下,可能是偶然为零

我猜是你想要的是

var totalRevenue = Context.Items
                   .Sum(x => x._ItemTransactions
                              .Sum(y => y.TransactionPrice * y.QuantitySoldTransaction)
                       );

基本上没有返回FirstOrDefault而是总和

或替代

var totalRevenue = Context.Items
                        .SelectMany(x => x._ItemTransactions)
                        .Sum(x => x.QuantitySoldTotal * x.TransactionPrice);

答案 2 :(得分:1)

这应该会给你预期的结果: -

var totalRevenue = Context.Items.SelectMany(x => x._ItemTransactions)
                                .Sum(x => x.QuantitySoldTotal * x.TransactionPrice);

首先使用SelectMany展开您的内部列表,即_ItemTransactions,然后您可以简单地调用 LINQ Sum方法来执行与您一样的总和在正常的名单上。