private static void containsCheck(City _city) { if (!cities.Contains(_city)) { cities.Add(_city); } }
// public method to add to the database if not already there public static void AddIfNotThere(City _city) { //containsCheck(_city); // won't work (easily) aside from String (see below) //simplestCheck(_city); // simple but cumbersome #region BEST SOLUTION - use LINQ to iterate through collection detecting if there or not if (!(cities.Any(cty => cty.Name == _city.Name))) cities.Add(_city); #endregion }
private static void simplestCheck(City _city) { bool foundCity = false; foreach (City cty in cities) { if (_city.Name == cty.Name) { foundCity = true; break; } } if (!foundCity) cities.Add(_city); }
private void btnAddCity_Click(object sender, RoutedEventArgs e) { string _city = tbkCity.Text; // read from textbox for data in City _newCity = new City { Name = _city, Pop = rnd.Next(10000000) }; // add to the collection if not already present DataStore.AddIfNotThere(_newCity); }