首页 > 解决方案 > 从 C# 中的列表更新对象

问题描述

我有以下内容:

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. 

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

标签: c#listobject

解决方案


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

public void UpdatePopulations(IEnumerable<Animal> newAnimals)
{
    var dictionary = newAnimals.ToDictionary<string, int>(a=>a.Name, a=>a.currentPopulation); // convert to dictionary, so that we have O(1) lookup during the search later. This process itself is O(n)
    foreach(var animal in animalList) // this will be O(n)
    {
        if(dictionary.ContainsKey(animal.Name))
        {
            animal.currentPopulation = dictionary[animal.Name].currentPopulation;
        }
    }
}

推荐阅读