在C#中从列表更新对象

时间:2018-04-25 05:33:13

标签: c# list object

我有以下内容:

public class Animal
    public int currentPopulation 
    public string name

   public Animal(int currentPopulation, string name){
       this.currentPopulation = currentPopulation;
       this.name = name;
   }

在另一堂课中我有:

public class MainClass

   <List><Animal>animalList
   ...

   lion = newAnimal(100, "Lion");
   cat = newAnimal(20, "Cat");
   dog = newAnimal(40, "Dog")

   animalList.add(lion);
   animalList.add(cat);
   animalList.add(dog);

我经常需要从服务器获取新数据并更新MainClass中的动物属性currentPopulation。目前我通过以下方式做到这一点:

public void UpdatePopulations(int lionPopulation, int catPopulation, int dogPopulation)

foreach(var item in animalList.where(n=>n.name=="Lion")){
   item.currentPopulation = lionPopulation;
}
... and the same for the cat and dog. 

我觉得我的解决方案很笨重,我想知道是否有更简洁的方法来更新列表中的对象。

4 个答案:

答案 0 :(得分:1)

使用list(动态容器)时,无法在不迭代的情况下找到元素。 提高效率的一种方法是在一条路径中更新List,而不是使用LINQ来查找元素。 像这样的东西

foreach(vat animal in animalList) 
{
    if (animal.name == "Lion")
        animal.currentPopulation = ...
    else if (animal.name == "...")
        animal.currentPopulation = ...

}

我建议您使用与列表不同的数据容器。 Dictionary<string, Animal> animals会更好地为您服务,因为您可以使用动物名称作为更新密钥。

答案 1 :(得分:1)

public void UpdatePopulations(Dictionary<string, int> populations)
{
    foreach(var population in populations)
        foreach(var animal in animalList.Where(x => x.name == population.Key))
            animal.currentPopulation = population.Value;        
}

<强>用法:

variableName.UpdatePopulations(new Dictionary<string, int> {
   ["Lion"] = 1000,
   ["Cat"] = 2000,
   ["Dog"] = 3000
});

答案 2 :(得分:1)

你也可以在'enum'的帮助下进行区分,如下所示,但你需要遍历列表来识别动物。

public enum AnimalName
{
    Lion,
    Cat,
    Dog
}

public class Animal
{
    public AnimalName Name { get; set; }

    public int Population { get; set; }

    public Animal(AnimalName name, int population)
    {
        Name = name;
        Population = population;
    }
}

public void UpdatePopulations(int lionPopulation, int catPopulation, int dogPopulation)
    {
        foreach (var animal in animals)
        {
            switch (animal.Name)
            {
                case AnimalName.Lion:

                    animal.Population = lionPopulation;
                    break;

                case AnimalName.Cat:

                    animal.Population = catPopulation;
                    break;

                case AnimalName.Dog:

                    animal.Population = dogPopulation;
                    break;
            }
        }
    }

答案 3 :(得分:1)

如果您要更新所有动物,将animalList转换为Dictionary几乎没有任何好处。我能想到的一些改进是接受IEnumerable,所以你可以自由更新某些或所有动物。

<span class="vcard author"><span class="fn"> Written by: <Admin rel="author"><?php the_author() ?> </Admin> </span></span>