[英]C# Dictionary HashSet
I have this Query i have to remove ORDER BY p.ID 我有这个查询我必须删除ORDER BY p.ID
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";
And i have this code i should remove if clause where i have to compare last element with current element from database. 我有这个代码我应该删除if子句,我必须比较最后一个元素与数据库中的当前元素。
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;
}
}
I have to remove Order By in query and then use Dictionary in method to get this data from database but i am new to Dictionary. 我必须在查询中删除Order By,然后在方法中使用Dictionary从数据库中获取此数据,但我是Dictionary的新手。 Can someone help me how to make it.
有人可以帮助我如何做到这一点。 Thanks!
谢谢!
If you need just to return Dictionary< int,Product > where key is product ID, then modify your return to: 如果您只需返回Dictionary <int,Product>其中key是产品ID,那么请将您的返回值修改为:
return listProducts.GroupBy(x => x.ID).
ToDictionary(y => y.Key, z => z.ToList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.