生成与LINQ的序列号 [英] Generate number sequences with LINQ
问题描述
我尝试写返回我的数字的所有可能组合的LINQ声明(我需要这一个测试,我由此受到启发的埃里克利珀的文章)。该方法的原型我称之为是这样的:
I try to write a LINQ statement which returns me all possible combinations of numbers (I need this for a test and I was inspired by this article of Eric Lippert). The method's prototype I call looks like:
IEnumerable<Collection<int>> AllSequences( int start, int end, int size );
的规则:
The rules are:
- 所有返回的藏品有
尺寸
- 集合中的数值要增加 $的长度b $ b
- 之间每隔数
启动
和结束
应使用
- all returned collections have a length of
size
- number values within a collection have to increase
- every number between
start
andend
should be used
所以调用 AllSequences(1,5,3)
应导致10集,每一个大小为3:
So calling the AllSequences( 1, 5, 3 )
should result in 10 collections, each of size 3:
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
现在,不知何故,我真的很想看到的纯LINQ 解决方案。我可以写一个非LINQ的解决方案我自己,所以请把没有精力没有LINQ的解决方案。结果
我试图在一个点为止结束了,我已经加入了一些与结果我的方法的递归调用 - 是这样的:从我在Enumerable.Range
Now, somehow I'd really like to see a pure LINQ solution. I am able to write a non LINQ solution on my own, so please put no effort into a solution without LINQ.
My tries so far ended at a point where I have to join a number with the result of a recursive call of my method - something like:
return from i in Enumerable.Range( start, end - size + 1 )
select BuildCollection(i, AllSequences( i, end, size -1));
但我不能管理它实施 BuildCollection()
在LINQ基地 - 甚至跳过此方法调用。你能帮助我吗?
But I can't manage it to implement BuildCollection()
on a LINQ base - or even skip this method call. Can you help me here?
推荐答案
我想我明白了。
IEnumerable<List<int>> AllSequences(int start, int end, int size)
{
if (size == 0)
return Enumerable.Repeat<List<int>>(new List<int>(), 1);
return from i in Enumerable.Range(start, end - size - start + 2)
from seq in AllSequences(i + 1, end, size - 1)
select new List<int>{i}.Concat(seq).ToList();
}
这篇关于生成与LINQ的序列号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!