如何使用LINQ而不是foreach循环?

时间:2014-08-29 20:28:49

标签: c# linq foreach

我想将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();
}

1 个答案:

答案 0 :(得分:2)

Aggregate LINQ method(又名fold/reduce operation)对r_{n+1} = f(r_n, x_n)中的n执行[0..len),并评估为r_{n+1}

在替换操作 1 ;

上应用折叠
fileAsString = itemList.Aggregate(fileAsString,
    (acc, item) => acc.Replace(match.Value, item.Value));

如果使用Regex.Matches,也可以在外循环上应用聚合。但是,使用LINQ 赢得会改变时间复杂度或使代码运行得更快 - Replace被称为相同次。

[注意:我再次查看了代码,并不会混淆为什么重复更换甚至会发生;以下可能不适用。替换的参数应该是其他方式吗?]

如果性能是个问题,那么使用正则表达式Replace with a match evaluator来处理文件替换可能会更好。也就是说,创建一个匹配所有项目的模式,尽可能最少 - 它可以像a|b|c一样具体或更一般。然后在匹配电梯内使用字典来查找替换值。


1 条件检查可以在外部移动内部循环,因为表达式在循环期间是固定的。虽然这不会影响我的运行时间[优先选择],因为它使LINQ稍微简单。