【发布时间】:2014-10-23 21:46:24
【问题描述】:
我想将 foreach 循环转换为 linq 查询,因为 itemList 可以有很多值,并且迭代该列表中的每个值很耗时。可以用 linq 来完成吗?
string fileAsString = File.ReadAllText(filePath);
Match match = Regex.Match(filePath, regx.ToString());
while (match.Success)
{
string itemToReplace = match.Groups["part"].Value;
//Use linq instead of the commented out area
//
//foreach (var item in itemList)
//{
// if (itemToReplace == macro.Name)
// {
// fileAsString = fileAsString.Replace(match.Value, item.Value);
// }
//}
//
match = match.NextMatch();
}
【问题讨论】:
-
Linq 没有摆脱循环。
-
是什么让您认为 Linq 会导致更快的执行?
-
linq 不会更快
-
fileAsString来自哪里? -
LINQ 并不神奇。如果你有很多替代品要执行,那将需要时间。仅仅让你的代码使用 LINQ 不会使这些替换更快。