我过去也遇到过类似的问题 - 我的数组中包含n个元素,如何从中获取两个元素的所有组合,而不重复?
IE中。如果数组是这样的:
var arr1 = new[] { "A", "B", "C", "D", "E"};
...结果应该是
AB
AC
AD
AE
BC
BD
BE
CD
CE
CD
你能帮助我吗?
答案 0 :(得分:2)
考虑以下代码......
var arr1 = new[] { "A", "B", "C", "D", "E" };
var combinations = new List<string>();
for(int i = 0; i < arr1.Length; i++)
{
for (int j = i + 1; j < arr1.Length; j++)
{
combinations.Add(string.Format("{0}{1}", arr1[i], arr1[j]));
}
}
祝你好运!
添加了参考资料的截图...
答案 1 :(得分:1)
var arr1 = new[] { "A", "B", "C", "D", "E" };
var combinations = new List<string>();
foreach (var i in arr1) {
foreach (var j in arr1) {
if((int)i.ToCharArray()[0] < (int)j.ToCharArray()[0]) {
combinations.Add(i + j);
}
}
}
现在组合列表包含所有组合!
答案 2 :(得分:1)
var myArray = new[] { "A", "B", "C", "D", "E" };
var myCombos = new List<string>();
for (int i = 0; i < myArray.Length; i++)
{
for (int j = (i + 1); j < myArray.Length; j++)
{
myCombos.Add(myArray[i] + myArray[j]);
}
}
现在我们有:
AB AC 广告 AE 公元前 BD 是 光盘 CE DE
答案 3 :(得分:0)
尝试以下(LINQ中的交叉连接)
var arr1 = new[] { "A", "B", "C", "D", "E"};
var result = (from i1 in arr1
from i2 in arr1.Where( i=> i[0]>i1[0])
select i1+i2).ToArray();
在ideone here
上的代码段结果AB
AC
AD
AE
BC
BD
BE
CD
CE
DE
答案 4 :(得分:0)
也许这个小LINQ查询:
var allCombinations = from str1 in arr1
from str2 in arr1
where str1.CompareTo(str2) < 0
select str1 + str2;
Console.Write(string.Join(",", allCombinations));
我的遗言与众不同,我认为结果是错字:AB,AC,AD,AE,BC,BD,BE,CD,CE,DE