Sined_121
Sined_121

Reputation: 13

C# Checking if list of objects contains an object with specific variable

I have a list that needs to have objects added or modified depending on if they already exist or not named countries. It contains Country type objects and they themselves contain a name, points and a Skier type object.

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
}

I have the other stuff figured out but I dont know what to put in the if.

Upvotes: 0

Views: 3055

Answers (3)

persian-theme
persian-theme

Reputation: 6638

you can use List<T>.Exists(Predicate<T>) Method . Specifies whether the List<T> contains the specified value.

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

Upvotes: 0

Caius Jard
Caius Jard

Reputation: 74605

countries.Any(c=>c.Name==name) will return you a Boolean true if name exists in the list, but you might be better swapping Any for FirstOrDefault and testing the result:

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

Upvotes: 1

Bryan Dellinger
Bryan Dellinger

Reputation: 5294

could you use first or default to check the list. if it is not there add it.

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

Upvotes: 0

Related Questions