这是我的函数,我在其中使用嵌套循环,如:
public string HGSearchNew(HolidayFeedService.PackageHolidays.SearchCriteria objsearchcriteria, dynamic search)
{
XmlDocument xdoc = new XmlDocument();
XmlNodeList ndepartures = xdoc.SelectNodes("Destinations/Departure");
string sFinalDeparture = objsearchcriteria.DepartureAirport.ToUpper();
for (int i = 0; i < objsearchcriteria.DepartureAirport.Split('|').Length; i++)
{
for (int j = 0; j < ndepartures.Count; j++)
{
if (objsearchcriteria.DepartureAirport.Split('|')[i].ToUpper() == ndepartures[j]["Name"].InnerText.ToUpper())
{
if (!sFinalDeparture.Contains(objsearchcriteria.DepartureAirport.Split('|')[i].ToUpper()))
sFinalDeparture += objsearchcriteria.DepartureAirport.Split('|')[i].ToUpper() + "|";
break;
}
}
}
return sFinalDeparture;
}
我希望使这段代码更有效,而不是使用循环,使用Contains或Any函数进行比较。 请帮助我?
答案 0 :(得分:5)
我认为您可以使用这种可读且高效的LINQ方法替换整个方法:
public string HGSearchNew(HolidayFeedService.PackageHolidays.SearchCriteria objsearchcriteria)
{
XmlDocument xdoc = new XmlDocument();
XmlNodeList ndepartures = xdoc.SelectNodes("Destinations/Departure");
string[] departureTokens = objsearchcriteria.DepartureAirport.Split('|');
var matches = ndepartures.Cast<XmlNode>()
.Select(node => node.Name)
.Intersect(departureTokens, StringComparer.InvariantCultureIgnoreCase);
return string.Join("|", matches);
}