【问题标题】:C# Checking if list of objects contains an object with specific variableC# 检查对象列表是否包含具有特定变量的对象
【发布时间】:2021-09-18 07:58:14
【问题描述】:

我有一个列表,需要根据对象是否已存在或未命名的国家/地区来添加或修改对象。它包含 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 中放什么。

【问题讨论】:

    标签: c# list linq


    【解决方案1】:

    您可以使用List&lt;T&gt;.Exists(Predicate&lt;T&gt;) 方法。指定List&lt;T&gt; 是否包含指定的值。

    if(countries.Exists(a => a.Name == name))
    {
        //change properties
    }
    else
    {
        //add
    }
    

    【讨论】:

      【解决方案2】:

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

      var country = countries.FirstOrDefault(c=>c.Name==name);
      if(country == default)
        //add
      else
        //update the properties of the `country` variable here
      

      【讨论】:

        【解决方案3】:

        您可以使用 first 还是 default 来检查列表。如果没有,请添加它。

        if (countries.FirstOrDefault(x => x.Name == name) == null){
               countries.add(new Country{Name = name});
            } else {
              // change country
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-07-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-10
          • 2022-11-09
          相关资源
          最近更新 更多