Tuesday, July 23, 2013

LINQ slow performance in checking almost 1 million data (Optimization Problem)

I have a code below which returns an object after satisfying a given condition.
1
2
3
result = listCountryStateCollection.Find(e => (e.CountryName.ToLower().Trim() == accomTempHotel.CityProvinceCountryName[0].CountryName.ToLower().Trim())  
      && (e.StateName.Trim().ToLower() == accomTempHotel.CityProvinceCountryName[0].StateName.ToLower().Trim())  
      && (e.SuburbCityName.Trim().ToLower() == accomTempHotel.CityProvinceCountryName[0].SuburbCityName.ToLower().Trim()));  
The problem I encountered was that, it was slow in getting the desired results. After doing optimization/code checking I came up with a simple solution. The solution is not to include string manipulations in your LINQ but instead the processing should be done using variables as defined below:
1
2
3
4
5
6
string country = accomTempHotel.CityProvinceCountryName[0].CountryName.ToLower().Trim();  
 string state = accomTempHotel.CityProvinceCountryName[0].StateName.ToLower().Trim();  
 string suburb = accomTempHotel.CityProvinceCountryName[0].SuburbCityName.ToLower().Trim();  
 result = listCountryStateCollection.Find(e => (e.CountryName == country)  
                   && (e.StateName == state)  
                   && (e.SuburbCityName == suburb)); 

Greg

0 comments:

Post a Comment