2009-06-10 89 views
0

用我下面的代码:分组 - LINQ到对象

using System.Collections.Generic; 
using System.Linq; 

namespace SampleGrouping 
{ 
internal class Program 
{ 
    private static void Main(string[] args) 
    { 
     var sample = new List<Samples> 
            { 
             new Samples{ParameterID = 11,MaterialID = 855,ProductID = 955,Quantity = 100}, 
             new Samples{ParameterID = 11,MaterialID = 855,ProductID = 955,Quantity = 200}, 
             new Samples{ParameterID = 12,MaterialID = 856,ProductID = 956,Quantity = 100}, 
             new Samples{ParameterID = 12,MaterialID = 856,ProductID = 956,Quantity = 400} 
            }; 
     // Result: Groupby ParameterID, MaterialID, ProductID 
     // ParameterID = 11,MaterialID = 855,ProductID = 955,Quantity = 300 
     // ParameterID = 12,MaterialID = 856,ProductID = 956,Quantity = 500 

     var enumerable = from s in sample 
         group sample by new 
              { 
               s.ParameterID, 
               s.MaterialID, 
               s.ProductID, 

              }; 
    } 
} 

internal class Samples 
{ 
    public int MaterialID { get; set; } 
    public int ParameterID { get; set; } 
    public int ProductID { get; set; } 
    public int Quantity { get; set; } 
} 
} 

我如何能实现结果为:列表作为

参数标识= 11,MaterialID = 855,产品ID = 955,数量= 300
参数标识= 12,MaterialID = 856,产品ID = 956,数量= 500

由于

回答

3

组以 “S”,而不是 “样品”。然后你可以根据需要选择数据:

var enumerable = 
    from s in sample 
    group s by new 
    { 
     s.ParameterID, 
     s.MaterialID, 
     s.ProductID, 
    } into GroupedSample 
    select new 
    { 
     GroupedSample.Key.ParameterID, 
     GroupedSample.Key.MaterialID, 
     GroupedSample.Key.ProductID, 
     TotalQuantity = GroupedSample.Sum(gs => gs.Quantity) 
    }; 
+0

谢谢你的工作。 – Sreedhar 2009-06-11 00:11:18