【问题标题】:List referencing a second List in C#列表引用 C# 中的第二个列表
【发布时间】:2015-06-01 20:02:53
【问题描述】:

我有一个类,其中包含两个用户定义类型列表,类别和属性。我试图让一个属性的一个组件来引用一个类别的一个组件。

我的分类列表如下所示

private static List<Category> GetCategories()
    {
        var categories = new List<Category> {
            new Category
            {
                CategoryID = 1,
                CategoryName = "Chip Life Cycle"
            },
            new Category
            {
                CategoryID = 2,
                CategoryName = "Abstraction"
            },
            new Category
            {
                CategoryID = 3,
                CategoryName = "Properties"
            },
            new Category
            {
                CategoryID = 4,
                CategoryName = "Location"
            },
        };

        return categories;
    }

这是我的属性列表。每个属性都有一个 CategoryID,接下来我希望 CategoryName 能够查看类别列表,找到匹配的 CategoryID 并获取 CategoryName。我怎么做?

private static List<Attribute> GetAttributes()
    {
        var Attributes = new List<Attribute> {
            new Attribute
            {
                AttributeID = 1,
                AttributeName = "Specification",
                Description = "Insertion",
                ImagePath="one.png",
                F_in = 0,
                F_out = 3,
                CategoryID = 1,
                CategoryName = **WHAT HERE?**
           },
            new Attribute 
            {
                AttributeID = 2,
                AttributeName = "Design",
                Description = "Insertion",
                ImagePath="two.png",
                F_in = 1,
                F_out = 2,
                CategoryID = 2,
                CategoryName = **WHAT HERE?**
           },
           new Attribute
            {
                AttributeID = 3,
                AttributeName = "Clock Grid",
                Description = "Location",
                ImagePath="thirty_three.png",
                F_in = 16,
                F_out = 0,
                CategoryID = 4
                CategoryName = **WHAT HERE?**
            },
        };
        return Attributes;
}

【问题讨论】:

  • 你有什么理由不从Attribute引用Category
  • 如果您的自定义Category 类真的只有两个属性,也许使用enum 而不是自定义类会更好?将其设为enum 可以保证1 始终具有相同的"Chip Life Cycle",而在您当前的实现中,您可以想象用相同的ID 和不同的名称来实例化两个不同的类别。
  • @OndrejTucny:这似乎是最好的。这看起来像是移植到 c# 中的关系数据库模式。

标签: c#


【解决方案1】:

您正在将类别中的某些信息“反规范化”为属性。具体来说,您正在重复 CategoryID 和 CategoryName。相反,只需引用 Category 本身,例如

new Attribute
{
    AttributeID = 1,
    AttributeName = "Specification",
    Description = "Insertion",
    ImagePath="one.png",
    F_in = 0,
    F_out = 3,
    Category = category1, // category1 is an instance of Category
 },

然后您可以访问例如第一个属性的类别名称如:

string name = GetAttributes().First().Category.Name;

【讨论】:

  • 我本来打算使用LINQ,但这个答案要好得多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-16
  • 1970-01-01
相关资源
最近更新 更多