C# List 集合优雅覆盖对象内容 - 使用索引器和 LINQ
在 C# 中,可以使用索引器直接访问 List 集合中的元素。因此,要覆盖 List 集合中的某个对象,可以通过索引器找到该对象并进行修改。
例如,假设有一个 List 集合包含多个 Person 对象,每个 Person 对象都有一个唯一的 ID 属性。现在需要根据 ID 属性覆盖某个 Person 对象的其他属性,可以使用以下代码:
List<Person> persons = new List<Person>();
// 添加多个 Person 对象到集合中
int targetId = 123; // 需要覆盖的对象的 ID
// 使用 LINQ 查找 ID 为 targetId 的 Person 对象
Person targetPerson = persons.FirstOrDefault(p => p.ID == targetId);
if (targetPerson != null)
{
// 覆盖目标 Person 对象的其他属性
targetPerson.Name = 'New Name';
targetPerson.Age = 25;
// ...
}
在上述代码中,首先使用 LINQ 查找 ID 为 targetId 的 Person 对象,然后判断是否找到了该对象。如果找到了该对象,则可以直接对该对象的属性进行修改,从而实现覆盖的目的。
原文地址: http://www.cveoy.top/t/topic/oCJy 著作权归作者所有。请勿转载和采集!