0

我有一个列表,需要根据对象是否已经存在或未命名的国家来添加或修改对象。它包含 Country 类型的对象,它们本身包含名称、点数和 Skier 类型的对象。

List<Country> countries = new List<Country>();
...inputs
string name= inputData[1];

if (find if a country with name exists inside countries list)
{
   change the country
}
else
{
   make new country
}

我已经弄清楚了其他的东西,但我不知道在 if 中放什么。

4

3 回答 3

1

countries.Any(c=>c.Name==name)如果列表中存在,将返回布尔值 true name,但您最好将 Any 替换为 FirstOrDefault 并测试结果:

var country = countries.FirstOrDefault(c=>c.Name==name);
if(country == default)
  //add
else
  //update the properties of the `country` variable here
于 2021-07-07T19:03:11.400 回答
0

您可以先使用还是默认使用来检查列表。如果它不存在添加它。

if (countries.FirstOrDefault(x => x.Name == name) == null){
       countries.add(new Country{Name = name});
    } else {
      // change country
    }
于 2021-07-07T18:59:03.600 回答
0

你可以使用List<T>.Exists(Predicate<T>)方法。指定 是否List<T>包含指定的值。

if(countries.Exists(a => a.Name == name))
{
    //change properties
}
else
{
    //add
}
于 2021-07-07T19:20:00.947 回答