2016-04-20 70 views
1

我有這個疑問我不得不刪除ORDER BY p.IDC#字典HashSet的

string query = "SELECT p.Price, p.ID, p.Name, c.Name as CategoryName, p.CategoryID, c.ID AS CategoryPK, c.ParentID," 
      + " o.ID as OrderID,o.ProductID,o.ClientCompanyID,o.Quentity" 
      + " FROM Products p LEFT JOIN Categories c ON p.CategoryID=c.ID LEFT JOIN Orders o ON o.ProductID=p.ID ORDER BY p.ID"; 

,我有這個代碼我應該刪除,如果where子句中我有最後一個元素與數據庫當前元素進行比較。

 static List<Product> GetProducts(SqlCommand command) 
    { 
     using (SqlDataReader reader = command.ExecuteReader()) 
     { 

      List<Product> listProducts = new List<Product>(); 
      while (reader.Read()) 
      { 

       Product product = null; 
       int productId = (int)reader["ID"]; 

       if (listProducts.Count >= 1 && listProducts[listProducts.Count - 1].ID == productId) 
       { 
        product = listProducts[listProducts.Count - 1]; 
       } 

       if (product == null) 
       { 
        product = new Product(); 

        product.ID = productId; 

        product.Name = (!reader.IsDBNull(reader.GetOrdinal("Name")) ? (string)reader["Name"] : null); 
        product.Price = reader.GetDecimal(reader.GetOrdinal("Price")); 
        product.CategoryID = reader.GetInt32(reader.GetOrdinal("CategoryID")); 
        Category newCat = new Category(); 
        newCat.ID = reader.GetInt32(reader.GetOrdinal("CategoryPK")); 
        newCat.CategoryName = reader.GetString(reader.GetOrdinal("CategoryName")); 
        newCat.Parent = (!reader.IsDBNull(reader.GetOrdinal("ParentID")) ? reader.GetInt32(reader.GetOrdinal("ParentID")) : 0); 
        product.Category = newCat; 

       } 

       Order order = new Order(); 
       order.ID = (!reader.IsDBNull(reader.GetOrdinal("OrderID")) ? (int?)reader["OrderID"] : null); 
       order.ClientCompanyID = (!reader.IsDBNull(reader.GetOrdinal("ClientCompanyID")) ? (int?)reader["ClientCompanyID"] : null); 
       order.ProductID = (!reader.IsDBNull(reader.GetOrdinal("ProductID")) ? (int?)reader["ProductID"] : null); 
       order.Quentity = (!reader.IsDBNull(reader.GetOrdinal("Quentity")) ? (int?)reader["Quentity"] : null); 

       product.Orders.Add(order); 
       listProducts.Add(product); 
      } 
      reader.Close(); 
      listProducts = listProducts.Distinct().ToList(); 
      return listProducts; 
     } 
    } 

我必須刪除訂單通過查詢,然後使用字典中的方法來從數據庫中獲得這個數據,但我是新來解釋。有人可以幫助我如何做到這一點。謝謝!

回答

0

如果你只需要返回字典< INT,產品>,其中關鍵的是產品ID,然後修改你的回報:

return listProducts.GroupBy(x => x.ID). 
    ToDictionary(y => y.Key, z => z.ToList());