c# 一个lsit对应多个list 嵌套

比如 动物 蔬菜 水果 是一个大的List 每个大的List 对应 一个List
动物 :猫 狗 牛 羊 。。。
蔬菜:白菜 西红柿 胡萝卜。。。
水果:苹果 香蕉 梨子 。。。。
举个例子谢谢

//普通一点就是

List<List<string>> allTypes = new List<List<string>>();

//animals : 
allTypes.add(new List<string>(){ "Cat", "Dog" });
//vegetables : 
allTypes.add(new List<string>(){ "Cabbage", "Tomato" });
//fruits : 
allTypes.add(new List<string>(){ "Apple", "Banana" });

//这样虽然可以但是有问题 因为虽然都在allTypes里,切不知道Cat是属于animals还是属于fruits

//所以声明一个类

public class Species {
    
    public string TypeName {get; set; }
    
    public List<string> Types { get; set;}

}

List<Species > allTypes = new List<Species >();

//animals : 
allTypes.add(  new Species (){ 
     TypeName  = "animals",
     Types =  new List<string>(){ "Cat", "Dog" })

//vegetables : 
allTypes.add(  new Species (){ 
     TypeName  = "vegetables ",
     Types =  new List<string>(){ "Cabbage", "Tomato" })

//fruits : 
allTypes.add(  new Species (){ 
     TypeName  = "fruits ",
     Types =  new List<string>(){ "Apple", "Banana" })
}

温馨提示:答案为网友推荐,仅供参考
相似回答