2
这是一个作业问题。帮助将foreach转换为Linq
我在我们的域模型上做了差异化,并且已经设置好了,以便我可以迭代检查域内的certian差异的操作列表。我传入差异函数以及对象图的前后状态,以在DiffContext中生成结果 - 稍后将用于设置调用另一服务的有效内容。不过,我已经做了一些修改,并需要与LINQ的语法
所以,我有以下的代码帮助...
public static IEnumerable<DiffContext> GetFirstDifference<T>(IEnumerable<Func<T, T, DiffContext>> diffOperations, T beforeState, T afterState)
{
return from op in diffOperations
let diff = op(beforeState, afterState)
where diff.FoundDifference
select diff;
}
其中我修改为使用Func<T, T, IEnumerable<DiffContext>>
而非以前Func<T, T, DiffContext>
的 - 因为现在我的diff操作可以返回多个差异。像这样..
public static IEnumerable<DiffContext> GetFirstDifference<T>(IEnumerable<Func<T, T, IEnumerable<DiffContext>>> diffOperations, T beforeState, T afterState)
{
foreach (var op in diffOperations)
{
foreach (var diff in op(beforeState, afterState))
{
yield return diff;
}
}
}
但现在我有这个嵌套的foreach,我希望有一些帮助将其转换为Linq等价物。你能帮我吗?
谢谢Jon Skeet。我现在有以下代替嵌套的foreach:
return from op in diffOperations
from diff in op(beforeState, afterState)
where diff.FoundDifference
select diff;