我有一些关系数据,即
- 来源(有很多类别)
- 类别(有很多产品)
- 产品
现在,如何使用 c# 中的类来处理这个问题?
只需将它们创建为 POCO(仅包含数据定义的简单 C# 类),例如
class source
{
public List<category> Categories = new List<category>();
}
class category
{
public category(string name)
{
Name = name;
}
public string Name {get;set;}
public List<product> Products = new List<product>();
}
class product
{
public product(string name)
{
Name = name;
}
public string Name { get; set; }
}
然后测试:
static void test()
{
product spoon = new product("spoon");
category cutlery = new category("cutlery");
cutlery.Products.Add(spoon);
source mystuff = new source();
mystuff.Categories.Add(cutlery);
}
你需要两个类Category
和Product
. 每个Product
都有Category
它所属的属性。您可以将它们存储在 中Dictionary<Category, List<Product>>
,然后您可以轻松查找给定类别的所有产品。
这是一个可能的实现,您甚至可以将这些类用作字典中的键,因为它们会覆盖GetHashCode
:
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public override int GetHashCode()
{
return CategoryId.GetHashCode();
}
public override bool Equals(object obj)
{
Category c2 = obj as Category;
if (c2 == null) return false;
return CategoryId == c2.CategoryId;
}
}
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
publlic Category Category { get; set; }
public override int GetHashCode()
{
return ProductId.GetHashCode();
}
public override bool Equals(object obj)
{
Product p2 = obj as Product;
if (p2 == null) return false;
return ProductId == p2.ProductId;
}
}
初始化(通常来自 DAL):
var cat1 = new Category(){CategoryId=1,Name="ABC"};
var cat2 = new Category(){CategoryId=2,Name="DEF"};
var products1 = new List<Product>(){
new Product(){ProductId=1,Name="Prod1",Category=cat1},
new Product(){ProductId=2,Name="Prod2",Category=cat1},
new Product(){ProductId=3,Name="Prod3",Category=cat1}
};
var products2 = new List<Product>(){
new Product(){ProductId=4,Name="Prod4",Category=cat2},
new Product(){ProductId=5,Name="Prod5",Category=cat2},
};
var categoryProducts = new Dictionary<Category, List<Product>>()
{
{ cat1, products1},
{ cat2, products2}
};
现在您可以查找给定类别的所有产品:
List<Product> products = categoryProducts[cat1];
来源可能是List<Category>
:
var source = new List<Category>();
// fill from DAL
foreach(Category cat in source)
foreach(Product product in categoryProducts[cat])
Console.WriteLine("Category:{0} Product:{1}", cat.Name, product.Name);