如何使用LINQ从某个数组中获取有序的元素对?例如, 我有:
int[] d = { 1, 2, 3 };
我需要:
{{1,1},{1,2},....,{3,3}}
我尝试了LINQ查询,但它返回
{{1,1},{2,2},{3,3},{1,1},{2,2},{3,3},{1,1},{2,2 },{3, 3}}
var pairs = d.SelectMany(a => d.Select(b => new[] { a, b }));
请帮我找错。
答案 0 :(得分:1)
像这样:
var result = d.SelectMany(a => d, Tuple.Create)
.Where(c=> c.Item1 <= c.Item2).ToArray();
答案 1 :(得分:-1)
此代码工作
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();