我正在编写一个验证一些城市的应用程序。验证的一部分是通过匹配国家代码和城市名称(或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