C# 替换作为属性/公共字段检索的对象列表中的元素
我试着做一件简单的事情——用另一个“更多最新”替换列表中的一个对象。问题是实际列表没有得到更新。列表定义并存储在myC# 替换作为属性/公共字段检索的对象列表中的元素,c#,.net,list,reference,C#,.net,List,Reference,我试着做一件简单的事情——用另一个“更多最新”替换列表中的一个对象。问题是实际列表没有得到更新。列表定义并存储在my数据提供程序类中: public class CountriesDataSet { List<Country> b; private IXmlBinder xmlBinder; public CountriesDataSet() { xmlBinder = new BasicXmlLoader()
数据提供程序
类中:
public class CountriesDataSet
{
List<Country> b;
private IXmlBinder xmlBinder;
public CountriesDataSet()
{
xmlBinder = new BasicXmlLoader();
Countries = xmlBinder.Load();
}
public List<Country> Countries;
public void Save()
{
xmlBinder.Save(Countries);
}
}
我可以看到该国家/地区已被新的
newCountry
实例替换,但没有更新countriesDataSet.Countries
,我做错了什么?解决此问题的正确方法是什么?使用newCountry
例如:
var countries = countriesDataSet.Countries;
Country country = countries.First(c => c.Id == id);
if (country != null)
{
country.State = newCountry.State;
country.Flag = NewCountry.Flag;
...
countriesDataSet.Save();
}
还是那样
:
使用
newCountry
例如:
var countries = countriesDataSet.Countries;
Country country = countries.First(c => c.Id == id);
if (country != null)
{
country.State = newCountry.State;
country.Flag = NewCountry.Flag;
...
countriesDataSet.Save();
}
还是那样
:
尝试替换“最新”值,而不是创建新实例
另外,First()
如果找不到匹配项,就会抛出异常,这显然是您所关心的,因为您测试了null
。使用FirstOrDefault
(或者如果最多需要一个匹配项,则使用SingleOrDefault
)
尝试替换“最新”值,而不是创建新实例
另外,First()
如果找不到匹配项,就会抛出异常,这显然是您所关心的,因为您测试了null
。使用FirstOrDefault
(或者如果最多需要一个匹配项,则使用SingleOrDefault
)
这看起来有点蹩脚,因为我必须复制这个类的所有值,难道没有任何模式可以为我覆盖吗?你能给出一些意见吗?为什么用IndexOf更新元素有效,而第一个不行?这看起来有点蹩脚,因为我必须复制这个类的所有值,有没有任何模式可以为我涵盖这一点?你能给我一些意见,为什么通过IndexOf更新元素是有效的,而第一个是无效的?
int index = listofelements.IndexOf(oldValue);
if(index != -1)
listofelements[index] = newValue;
var countries = countriesDataSet.Countries;
Country country = countries.FirstOrDefault(c => c.Id == id);
if (country != null)
{
country.SomeProperty = newCountry.SomeProperty;
country.SomethingElse = newCountry.SomethingElse;
countriesDataSet.Save();
}
var countries = countriesDataSet.Countries;
var index = countries.FindIndex(c => c.Id == id));
if (index >= 0)
countries[index] = newCountry;
countriesDataSet.Save();