2011-05-24 56 views
1

我有以下列表IGrouping麻煩

class Programm 
    { 

     public static void Main(string[] args) 
     { 
      List<Service> Services =new List<Service> 
      { 
        new Service 
         { 
         Name = "name1", 
         Prices = new List<BEPrice> 
          { 
          new BEPrice 
           { 
           Price = 120, 
           Quantity = 3 
           } 

          } 
         }, 
       new Service 
        { 
        Name = "name2", 
        Prices = new List<BEPrice> 
         { 
         new BEPrice 
          { 
          Price = 123, 
          Quantity = 3 
          } 

        } 
       }, 

       new Service 
       { 
       Name = "name3", 
       Prices = new List<BEPrice> 
       { 
        new BEPrice 
        { 
         Price = 100, 
         Quantity = 3 
        } 

        } 
       }, 

       new Service 
       { 
       Name = "name4", 
       Prices = new List<BEPrice> 
       { 
        new BEPrice 
        { 
        Price = 900, 
        Quantity = 8 
        } 

       } 
      } 
     }; 






    } 


    public class Tariff 
    { 

     public string Name { get; set; } 
     public List<BEPrice> Prices { get; set; } 
    } 


    public class Service 
    { 

     public string Name { get; set; } 
     public List<BEPrice> Prices { get; set; } 
     public Tariff Tariff; 
    } 


    public class BEPrice 
    { 

     public decimal Price { get; set; } 
     public int Quantity { get; set; } 

    } 

我想要一個結果作爲

Tariff-1 -> Name - "blabla", Prices = { 
      Price1 = {Price = 343, Quantity = 3}, 
      Price2 = {Price = 900, Quantity = 8} } 

關稅第一價格價格1 是總和,, 3(數量)個月。

這裏是我的成功學嘗試

foreach (var groupedPrices in Services.Select(s => s.Prices.GroupBy(p => p.Quantity))) 
      { 

       foreach (var p in groupedPrices.Select(x => x.Key)) 
        Console.WriteLine(p); 


       foreach (var price in groupedPrices) 
       { 

        _prices.AddRange(price.Select(p => p)); 
       } 

      } 
+2

請重新格式化您的代碼,以使用更少的壓痕。 8個字符的縮進確實很難以像Stack Overflow這樣的窄格式讀取代碼。 – 2011-05-24 06:41:06

+1

@Jon Skeet:我不明白爲什麼有人會在C#中使用超過2個空格:) – leppie 2011-05-24 06:42:13

回答

3

不知道是什麼名字布拉布拉,但是這是你如何能得到的價格部分

var prices = Services 
    .SelectMany(arg => arg.Prices) 
    .GroupBy(arg => arg.Quantity) 
    .Select(arg => new { Price = arg.Sum(x => x.Price), Quantity = arg.Key }) 
    .ToList(); 
+0

這是完美的! – Alexandre 2011-05-24 07:00:25