我将要编写一个验证城市的应用程序。其中一部分验证是通过匹配国家代码和城市名称(或备选城市名称)来检查城市是否已经在列表中。
我将我的现有城市列表存储为:
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<>更快的集合用于此类比较,并且是否有更快的比较函数可以替换FirstOrDefault()?
编辑
我忘记发布我的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()) + ".");
}