2011-06-10 156 views
0

我需要一种方法来减少列表或计算“总计”。我有一堂课,让我们称之为产品。 Prod包含4个值。一个是产品的名称,ID,序列号和数量。基本上我有一个产品,但有两个不同的序列号。所以,当我从我的查询中得到我的数据时,我有两个项目,我想将它们视为单个项目。我该如何去使用LINQ或其他的东西(我不能对他们进行预告,还有更多的类成员,这需要一段时间,再加上看起来很糟糕)。我希望能够使用2个实例并合并其序列号(而不是仅添加Serail1 - Serial 2)并一起计算数量。在列表中组合两个项目

+0

你可以举个例子吗?列表样本的数据?未标记答案 – Kiquenet 2016-09-29 07:12:57

回答

0

使用join运算符并将它们放在Tuple中。然后你可以在元组上调用更多的LINQ或迭代它们。

var combinedProducts = 
    from product1 in products1 
    join product2 in products2 on product1.serial equals product2.serial 
    select Tuple.Create(product1, product2); 

// Use LINQ to calculate a total  
combinedProducts.Sum(combined => combined.Item1.count * combined.Item2.price); 

// Or use foreach to iterate over the tuples 
foreach (var combined in combinedProducts) { 
    Console.WriteLine("{0} and {1}", combined.Item1.name, combined.Item2.name); 
} 
1

我想你想要的是Linq分组功能(见GroupBy - Simple 3)。这应该给你一个序列号和他们的数量清单:

public void Linq42() 
{ 
    List<Prod> products = GetProductList(); 

    var serialCombined = 
     from p in products 
     group p by p.SerialNumber into g 
     select new { SerialNumber = g.Key, Total = g.Count() }; 
}