首页 > 解决方案 > 从 Linq 查询中提取方法

问题描述

我有以下静态方法,它从IEnumerable<int>pythagorean 返回所有可能的三元组组合。例如:对于int[] array = {1, 2, 3, 4, 5},它将返回new[]{{3, 4, 5}, {4, 3, 5}}

 public static IEnumerable<IEnumerable<int>> GetPythagoreanNumbers(IEnumerable<int> array)
    {
        return array.SelectMany((a, i) =>
        {
            var inner = array.Skip(i + 1);
            return inner.SelectMany((b, j) =>
                inner.Skip(j + 1)
                    .SelectMany(c => GetTriplePermutations(a, b, c)));
        });
    }

现在,GetTriplePermutations()返回一个IEnumerable<IEnumerable<int>>,它表示从收到的 3 个整数 (a, b, c) 构建的数组集合。基本上,查询返回数组中 3 个元素的所有可能排列,从左到右开始。(例如:){1, 2, 3, 4, 5} => new[]{ {1, 2, 3}, {1, 2, 4}, {1, 2, 5}, {2, 3, 4}, {2, 3, 5}, {3, 4, 5} }。从查询返回的所有三元组中,GetTriplePermutations()只选择满足我条件的三元组。

我已经设法让它正常工作,但是,当我重构时,我发现我的查询有点重复,这意味着它应用了相同的连续 ext 方法模式:

array.SelectMany((a, i)).Skip(x + 1).SelectMany((b, j)).Skip(y + 1)

因此,为了消除重复,我试图以某种方式提取一种方法,该方法允许将代码转换为如下内容:

return OddMethod(array).SelectMany(c => GetTriplePermutations(a, b, c)));

现在,我不知道该怎么做,因为我的代码的一部分是由 Linq 查询返回的。我在想这个“OddMethod”的签名应该是这样的:

IEnumerable<IEnumerable<int>> OddMethod(int[] array)

,但不能再进步了。有什么想法可以实现这种“方法提取”吗?谢谢!:)

标签: c#.netlinqanonymous-function

解决方案


你总是可以定义一个扩展方法来覆盖你的逻辑并使你的代码更具可读性。

阅读更多:https ://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-implement-and-call-a-custom-extension-method

伪代码:

public static IEnumerable<IEnumerable<int>> GetTriplePermutations(tis IEnumerable<int> array)
{
    return array.SelectMany((a, i)).Skip(x + 1).SelectMany((b, j)).Skip(y + 1)
}

您可以通过使用调用此函数OddMethod(array).GetTriplePermutations();


推荐阅读