c# - 从 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.
我觉得我的解决方案很庞大,我想知道是否有更简洁的方法来更新列表中的对象。
解决方案
如果您要更新所有动物,那么将 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;
}
}
}
推荐阅读
- python - 如何返回导致包含 True 标志的关键字
- android - 保存到画廊的图像被旋转并且日期错误(1970)
- php - laravel 如何从自定义请求对象进行验证?
- javascript - 从 URL(动态数据)在页面中发布 JSON 数据
- javascript - 带有动作的倒数计时器
- c# - 如何将特定的 json 字符串反序列化为 ASP.NET MVC 模型?
- reactjs - 你不应该在外面使用
错误 - python - Pandas:如果 df1 中的子字符串存在于 df2 的字符串中,则加入两个数据帧(如果字符串包含子字符串)
- sql - 合并2个没有主键的表
- html - 如何在用户界面(AngularJs/HTML)中显示 git 命令结果?