更新一个列表中的属性值与另一个列表中的匹配项目的属性值的平均值

问题描述:

我有两个列表,需要更新第一个列表中的所有项目的属性值,其中所有匹配项目的属性值的平均值另一个列表。更新一个列表中的属性值与另一个列表中的匹配项目的属性值的平均值

class transaction 
{ 
    public string orderId; 
    public string parentOrderId; 
    public int quantity; 
    public decimal marketPrice; 
    public decimal fillPrice; 
} 

List<transaction> makerTransactions = new List<transaction>() 
{ 
    new transaction(){ 
        orderId = "1", 
        parentOrderId = "1", 
        quantity = 100, 
        marketPrice = 75.87M, 
        fillPrice = 75.87M 
        } 
}; 

List<transaction> takerTransactions = new List<transaction>() 
{ 
    new transaction(){ 
        orderId = "2", 
        parentOrderId = "1", 
        quantity = 50, 
        marketPrice = 75.97M, 
        fillPrice = 75.97M 
        }, 
    new transaction(){ 
        orderId = "3", 
        parentOrderId = "1", 
        quantity = 50, 
        marketPrice = 75.85M, 
        fillPrice = 75.85M 
        } 
}; 

试图使这与LINQ扩展方法的工作,但不能找出正确的方法。

makerTransactions.All(mt => mt.fillPrice = takerTransactions 
       .Where(tt => tt.parentOrderId == mt.orderId) 
       .Average(ta => ta.fillPrice)); 

试试这个:

makerTransactions.ForEach(mt => mt.fillPrice = takerTransactions 
    .Where(tt => tt.parentOrderId == mt.orderId) 
    .Average(ta => ta.fillPrice)); 

全部是一个扩展方法。它会告诉你一个集合中的所有元素是否符合某种条件,显然,这不是你所需要的。

为了使之更有效率,首先创建一个字典,并用它来采取从场均数据:

var priceDictionary = takerTransactions 
    .GroupBy(tt => tt.parentOrderId) 
    .ToDictionary(grp => gr.Key, grp => grp.Average(ta => ta.fillPrice)); 

makerTransactions.ForEach(mt => mt.fillPrice = priceDictionary[mt.orderId]); 
+2

我会创造orderId'的'字典(键)和'average'(值)(第使用LINQ语句和'ToDictionary')。计算每次迭代的平均值非常昂贵。 –

+0

@GertArnold是的,你是对的。谢谢 –

+0

@GertArnold你能否详细解释一下你的建议?我仍然需要迭代第一个列表中的所有项目,在第二个列表中搜索匹配的记录并对匹配进行平均。 – ddrjca