いくつかの都市を検証するアプリケーションを作成しています。検証の一部は、国コードと都市名 (または代替都市名) を照合して、都市が既にリストに含まれているかどうかを確認することです。
既存の都市リストを次のように保存しています。
public struct City
{
public int id;
public string countrycode;
public string name;
public string altName;
public int timezoneId;
}
List<City> cityCache = new List<City>();
次に、国コードや都市名などを含む場所文字列のリストを作成します。この文字列を分割して、都市が既に存在するかどうかを確認します。
string cityString = GetCity(); //get the city string
string countryCode = GetCountry(); //get the country string
city = new City(); //create a new city object
if (!string.IsNullOrEmpty(cityString)) //don't bother checking if no city was specified
{
//check if city exists in the list in the same country
city = cityCache.FirstOrDefault(x => countryCode == x.countrycode && (Like(x.name, cityString ) || Like(x.altName, cityString )));
//if no city if found, search for a single match accross any country
if (city.id == default(int) && cityCache.Count(x => Like(x.name, cityString ) || Like(x.altName, cityString )) == 1)
city = cityCache.FirstOrDefault(x => Like(x.name, cityString ) || Like(x.altName, cityString ));
}
if (city.id == default(int))
{
//city not matched
}
空港や国などの他のオブジェクトも同じ方法でチェックしているため、これは多くのレコードにとって非常に遅いです。これをスピードアップする方法はありますか?List<> よりも高速なこの種の比較のコレクションはありますか? また、FirsOrDefault() という高速な比較関数はありますか?
編集
Like() 関数を投稿するのを忘れていました:
bool Like(string s1, string s2)
{
if (string.IsNullOrEmpty(s1) || string.IsNullOrEmpty(s2))
return s1 == s2;
if (s1.ToLower().Trim() == s2.ToLower().Trim())
return true;
return Regex.IsMatch(Regex.Escape(s1.ToLower().Trim()), Regex.Escape(s2.ToLower().Trim()) + ".");
}