笛卡尔数组的平方
本文关键字:数组 笛卡尔 | 更新日期: 2023-09-27 18:13:04
我如何从一些数组中获得有序的元素对,使用LINQ?例如,我:
int[] d = { 1, 2, 3 };
我需要:
我尝试了LINQ查询,但它返回{{1,1}, {1,2}, ...., {3,3}}
{{1}, {2,}, {3}, {1}, {2,}, {3}, {1}, {2,}, {3,3}}
var pairs = d.SelectMany(a => d.Select(b => new[] { a, b }));
像这样:
var result = d.SelectMany(a => d, Tuple.Create)
.Where(c=> c.Item1 <= c.Item2).ToArray();
此代码有效
int[] d = { 1, 2, 3 };
var query = (from elem1 in d
from elem2 in d
where elem1>= elem2
select elem1< elem2? new List<int>() { elem1, elem2 }: new List<int>() { elem2, elem1 }
).Distinct().ToArray();