0

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.

0

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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
    }

Comments

0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.