[英]Optimal way to get Pairs of Objects from a List C#
I have a List of objects named Team and I want the optimal way to get all the possible pairs of objects.我有一个名为 Team 的对象列表,我想要获得所有可能的对象对的最佳方式。 I've written an example:
我写了一个例子:
public void GenerateMatches(Team team)
{
for(int i = 0; i < team.Count-1; i++)
{
for (int j = i + 1; j < team.Count; j++)
{
Console.WriteLine("Match:" + team[i].Name + " vs " + team[j].Name);
}
}
}
This is far from optimal but it works.这远非最佳,但它有效。 Any better ideas?
有什么更好的想法吗?
Here is the solution :这是解决方案:
You will need to iterate Teams
and take pairs of currentTeam
with all the next indexes:您将需要迭代
Teams
并使用所有下一个索引对currentTeam
进行处理:
List<int> MyList = new List<int> {1, 2, 3, 4, 5, 6, 7, 8, 9}; // sample input
List<KeyValuePair<int, int>> MyPairs = new List<KeyValuePair<int, int>>(); // prepare final result
for (int i = 0; i < MyList.Count; i++)
for (int j = i + 1; j < MyList.Count; j++)
if(j < MyList.Count)
MyPairs.Add(new KeyValuePair<int, int> (MyList[i], MyList[j]));
Then to display :然后显示:
foreach (var pair in MyPairs)
Console.WriteLine(pair.Key +" vs "+ pair.Value);
Part of the output :部分输出:
The optimal running time is n(n - 1)/2 , since this is the number of ordered pairs.最佳运行时间是n(n - 1)/2 ,因为这是有序对的数量。
Your solution is optimal.您的解决方案是最佳的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.