开发者

Help converting foreach to Linq

this is a homework question.

I am doing diffs on our domain model and I've set it up so that I can iterate a list of operations that check for certian differences within the domain. I pass in the differencing function and the before and after states of the object graph to produce a result in the DiffContext - which is used later to set up a payload for calling another service. But I've made some changes and need help with the Linq syntax

So, I have the following code ...

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;
}

Which I modified to use Func<T, T, IEnumerable<DiffContext>> instead of the previous Func<T, T, DiffContext> - because now my diff operations can return multiple differences. Like so..

public static IEnumerable<DiffContext> GetFirstDifference<T>(IEnumerable<Func<T, T, IEnumerab开发者_C百科le<DiffContext>>> diffOperations, T beforeState, T afterState)
{
    foreach (var op in diffOperations)
    {
        foreach (var diff in op(beforeState, afterState))
        {
            yield return diff;
        }
    }
}

But now I have this nested foreach and I'd like some help converting it to the Linq equivalent. Can you help?

Thanks Jon Skeet. I now have the following instead of the nested foreach:

    return from op in diffOperations
           from diff in op(beforeState, afterState)
           where diff.FoundDifference
           select diff;


Yup - you want two "from" clauses, basically - that performs a flatten operation. This uses the SelectMany LINQ operator.

Given that this is homework, I'm reluctant to post the full code - but I will say it's a three-line LINQ query (using the natural line breaking). Think about what you want "from" each collection...

Just add comments if that's not enough of a hint.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜