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

时间:2016-07-22 15:21:57

标签: c# list

我有一个名为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);
            }
        }
    }

这远非最佳,但可行。有更好的想法吗?

2 个答案:

答案 0 :(得分:2)

以下是解决方案

您需要对所有下一个索引进行迭代require_once __DIR__.'../public_html/alpha/index.php'; 并成对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]));

部分输出

enter image description here

答案 1 :(得分:0)

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