gpt4 book ai didi

c# - 嵌套循环的代码效率 c#

转载 作者:太空宇宙 更新时间:2023-11-03 19:52:26 27 4
gpt4 key购买 nike

这是我使用嵌套循环的函数,例如:

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 函数进行比较。请帮帮我好吗?

最佳答案

我认为您可以用这种可读且高效的 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);
}

关于c# - 嵌套循环的代码效率 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37301446/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com