列表引用C#中的第二个List

时间:2015-06-01 20:02:53

标签: c#

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

我的类别列表如下所示

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;
}

1 个答案:

答案 0 :(得分:4)

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

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;