c# - 从 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)
,但不能再进步了。有什么想法可以实现这种“方法提取”吗?谢谢!:)
解决方案
你总是可以定义一个扩展方法来覆盖你的逻辑并使你的代码更具可读性。
伪代码:
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();
推荐阅读
- javascript - 上传文件时 csrf 令牌无效
- angular-ngrx-data - 使用 @ngrx/data 为实体集合实现多个状态
- html - 使用 JQuery 从数组对象添加链接
- javascript - 正则表达式:在每个“:”之后提取字符串
- angular - 带有参数的角度获取请求到 Flask REST 资源不起作用
- reactjs - 如何在 ReactJS 中导出多个列表?
- scala - 使用scala查找spark中列值的差异
- apache-kafka - Kafka ISR 不断缩小和不同步副本
- javascript - JavaScript获取与另一个字段集中的每个值对应的字段值数组
- c# - 使用多个 async/await 复制文件时出现问题