繁体   English   中英

从列表 C# 中获取对象对的最佳方法

[英]Optimal way to get Pairs of Objects from a List C#

我有一个名为 Team 的对象列表,我想要获得所有可能的对象对的最佳方式。 我写了一个例子:

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);
            }
        }
    }

这远非最佳,但它有效。 有什么更好的想法吗?

这是解决方案

您将需要迭代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]));

然后显示

    foreach (var pair in MyPairs)
        Console.WriteLine(pair.Key +" vs "+ pair.Value);

部分输出

在此处输入图片说明

最佳运行时间是n(n - 1)/2 ,因为这是有序对的数量。
您的解决方案是最佳的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM