So I have this array: int[] M = { 1, 2, 3, 4, 5 }
, and from this array I want to generate combinations of 3 numbers at a time without repetition using Linq.
I have already succeeded to generate these combinations using 3 for loops:
List<(int,int,int)> combinations = new List<(int,int,int)>();
for(int i = 0; i < M.Length / 2 + 1; i++)
{
for(int j = i+1; j < M.Length - 1; j++)
{
for(int k = j+1; k < M.Length; k++)
{
combinations.Add((M[i], M[j], M[k]));
}
}
}
This is what I tried using Linq:
var combinationsL = M.SelectMany(i => Enumerable.Range(0, M.Length / 2 + 1)
.SelectMany(j => Enumerable.Range(1, M.Length - 1 - i)
.SelectMany(k => Enumerable.Range(2, M.Length- j)
.Select(item => new int[] { M.ElementAt(i), M.ElementAt(j),
M.ElementAt(k) }))));
and it doesn't give me the expected result.
This is the expected result:
var combo = new[] { (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) };
Can anyone tell me what I did wrong?
No need to install libraries, this is the formula you're looking for:
var result = M.SelectMany((x, i) =>
M.Skip(i + 1).SelectMany((y, j) =>
M.Skip(i + j + 2).Select(z => new int[] { x, y, z })));
The MoreLINQ library , available as a NuGet package , has a Subsets
method overload that:
Returns a sequence of
IList<T>
representing all subsets of a given size that are part of the original sequence.
It should match your need.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.