2015-05-15 123 views
0

我有db實體orderItems和類OrderCountet 其中我有方法Counting根據orderItems在我的商店中最流行的產品進行統計。字符串和值重複列表

代碼後,下面我有輸出是這樣的:

Name   Quantity 
Chocapic  7 
Bread   2 
Chocapic  7 
Bread   2 
Cheese   3 

我想使這個名單沒有重複。 因爲現在輸出說,我有14個chocapic在這個列表中,但我只有7. 我試圖搜索一些如何實現,但我只發現HashSet。 也有不同的列表解決方案,但只適用於字符串或整數列表。

Public class Statistic 
{ 

    //ProductName 
    String Name {get: set;} 
    //quantity product 
    Int quantity {get: set;} 
     //class for counting 
    and OrderCounter OrderCounter{get: set;} 

} 

public class OrderCounter 

{ 
     private List<Statistic> list_statistic =new List<Statistic>(); 

public List<Statistic> List_statistic 
{ 

    get{ return list_statistic ;} 
} 

public void Counting() 
{ 
     foreach(Order k in db.OrderItems) 
    { 
      int sum=0; 
      Statistic temp =new Statistic(); 

     foreach(Product product in db.Products) 
     { 
       if(product.Id==k.productId 
       { 

       sum+=sum+k.quantity; 
       } 
      temp.quantity=sum; 
      temp.Name=k.Product.Name(); 
      list_statistic.Add(temp); 
     } 
    } 

    if(orders.product.Id==product.Id) 
    { 
     sum+=suma +k.quantity; 
    } 
} 

enter image description here

+1

爲什麼不'字典'? –

+1

這不是你想要的:'sum + = sum + k.quantity;'你只需要'sum + = k.quantity;'。 – Gene

+0

雖然這是你的問題最少的。如果您需要幫助,請花時間確保代碼實際編譯/ etc:[編寫完美問題](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/) – Gene

回答

1

您可以嘗試使用以下foreach循環在Counting()方法,

 foreach (Order k in db.OrderItems) 
     { 
      int sum = 0; 

      foreach (Product product in db.Products) 
      { 
       Statistic temp = new Statistic(); 
       if (product.Id == k.productId) 
       { 
        sum += k.quantity; 
       } 
       temp.quantity = sum; 
       temp.Name = k.Product.Name(); 
       if (!list_statistic.Exists(x => string.Compare(x.Name, temp.Name, true) == 0)) 
       { 
        list_statistic.Add(temp); 
       } 
      } 
     } 

希望這有助於...

+0

謝謝;)經過一些修改後,我現在只能計算重複值。 –

2

這是因爲你一直添加相同的對象添加到列表:temp在循環之前創建一次,並得到多次添加。

移動這條線內循環來解決這個問題:

Statistic temp =new Statistic(); 

如果可以,給Statistics一個構造函數namequantity,使對象不可改變通過改變其制定者的無障礙private

0

這是工作:)

public void Counting() 
     { 
      foreach (Order k in db.OrderItems) 
      { 
       int sum = 0; 
       Statystyki temp = new Statystyki(); 
       foreach (Product product in db.Products) 
       { 

        if (product.Id == k.productId) 
        { 
         sum += k.quantity; 
        } 
       } 

       temp.Nazwa = k.Product.Name; 
       if (!lista_statystyk.Exists(x => string.Compare(x.Nazwa, temp.Nazwa, true) == 0)) 
       { 

        temp.suma = sum; 
        lista_statystyk.Add(temp); 
       } 
       else if (lista_statystyk.Exists(x => string.Compare(x.Nazwa, temp.Nazwa, true) == 0)) 
       { 
        temp.suma += sum; 
        lista_statystyk.Add(temp); 
       } 
      } 
     }