我正在編寫一個驗證一些城市的應用程序。驗證的一部分是通過匹配國家代碼和城市名稱(或alt cityname)來檢查城市是否已經在列表中。最快的方法來比較c中的對象#
我儲存我現有的城市名單爲:
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()嗎?
編輯
我忘了我的後贊()函數:
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()) + ".");
}
我相信你最大的性能問題是'Like'運營商,這是昂貴的。你不能簡單地使用一個相等比較器嗎? – 2012-07-24 13:06:06
你能告訴我們你是怎麼稱呼這個比較方法 – 2012-07-24 13:09:36
我建議不要在內存中這樣做,原因有兩個。首先是因爲你已經看到這個機制存在明顯的性能問題,其次是因爲你在內存中保存了大量的信息,嚴格來說是爲了搜索它。這適用於數據庫服務器,並且往返開銷非常微不足道。 – 2012-07-24 13:15:26