如何将列表添加到列表中

时间:2015-03-05 08:15:50

标签: c# list c#-4.0 multidimensional-array

我有一个动物类型,包含动物类型,每个动物都有一个访问列表,每次访问治疗时都会添加信息。 不知何故,我无法弄清楚如何将访问列表添加到动物列表animalList.Add(listHealth)?????不工作

List <Animal> animalList = new List <Animal>{typeOfAnimal = "Cat"};
DetailsOfAnimal da;

public class Animal
{
   public string typeOfAnimal;
   List <HealthList> listHealth = new List <HealthList>
}

public class HealthList
{
  public Date visit {get;set;}
  public string symptoms  {get;set;}
 }

.......
if new animal 
animalList = new List <Animal>;
// Add details to animal
da = new HealthList{visit = "2005-03-05", symptoms = "bad stomach"}
  List <HealthList> listHealth = new List <HealthList>
listHealth .Add(da);

animalList.Add(listHealth)   ???? Not working how to do that

3 个答案:

答案 0 :(得分:3)

Animal animal = new Animal();
animal.typeOfAnimal = "Cat";

da = new HealthList{visit = "2005-03-05", symptoms = "bad stomach"}
animal.listHealth.Add(da); // animal already has a non-null List<HealthList>

animalList.Add(animal);

您正在撤消操作的顺序...最好先创建Animal(已包含listHealth),然后填充listHealth。您可以在animalList.Add结束时或new Animal()之后立即List<Animal> animalList = new List <Animal>{typeOfAnimal = "Cat"}; 。没有区别。

这是错误的:

List<Animal> animalList = new List<Animal>();

应该是

List<Animal> animalList = new List<Animal> { new Animal { typeOfAnimal = "Cat" } };

{{1}}

答案 1 :(得分:3)

class Program
{
    private static List<Animal> animalList = new List<Animal>();

    static void Main(string[] args)
    {
        Animal animal = new Animal() { TypeOfAnimal = "Dog" };
        // created a new animal

        animal.HealthList.Add(new Health() 
                              { 
                                  Visit = new DateTime(2014, 03, 05),
                                  Symptoms = "Herby is permanantly scratching his nose" 
                              });
        // added a new instance of Health to its HealthList
        // if you allready have a List<Health> the you can call
        // animal.HealthList.AddRange(theList); 
        // works as well with any other IEnumerable<Health>
        animalList.Add(animal);
    }
}

public class Animal
{
    private List<Health> healthList = new List<Health>(); 
    // the default accessmodifier for a classmember is private
    // you can write it too so you better understand what's going on

    public string TypeOfAnimal { get; set; }

    public List<Health> HealthList { get { return healthList; } }
    // add a readonly property for the list so you can access it from outside the class
}

public class Health 
// change this name for "HealthList" is missleading you
// because it would imply that it is a collection
{
    public DateTime Visit { get; set; }
    public string Symptoms { get; set; }
}

答案 2 :(得分:0)

可以将一个列表添加到另一个列表:

    list1.AddRange(list2);

另见:https://msdn.microsoft.com/en-us/library/z883w3dc%28v=vs.110%29.aspx

您无法将另一种类型的列表添加到另一种类型。

在您的情况下,animalList是Generic Type Animal,您正在尝试向其添加整个List。