在C#中,如何排序该项目列表中哪个项目更大? [英] In C#, how can I order this list of objects by which item is greater?
问题描述
我有一个名为Team的简单类,如下所示:
I have a simple class called Team, that looks like this:
public class Team
{
public Team ParentTeam;
public string Name;
}
因此,它有一个名称和对另一个团队(其上级团队)的引用.
So it has a Name and a reference to another team that is its Parent Team.
我现在有一个从功能中返回的团队列表
I now have a list of Teams that I am getting back from a function
List<Team> list = GetTeamsList();
给出一些假设:
- 除一个团队(顶级团队)外,所有团队都有一个ParentTeam团队
- 列表中返回的每个团队都是同一层次结构的一部分,并且只有一个层次结构(在同一级别"中没有2个团队)
我现在需要获取此函数的结果并按层次结构对列表进行排序
I now need to take the results of this function and order the list by the hierarchy
因此,假设我们有以下团队信息:
So imagine we have the following team information:
|| Team Name || Parent Team Name ||
||-----------||------------------||
|| Team A || Team B ||
|| Team B || Team C ||
|| Team C || Team D ||
|| Team D || null ||
,但是GetTeamsList()函数以任何随机顺序返回团队.例如,它可能会回来列出以下内容:
but the GetTeamsList() function returns the teams in any random order. For example, it might come back list this:
var teamA = GetTeamA();
var teamB = GetTeamB();
var teamC = GetTeamC();
var teamD = GetTeamD();
List<Team> list = new List() { teamD, teamA, teamB, teamC };
我需要在此列表上重新排序,因此它看起来像这样:
where I need to reorder this list so it looks like this:
List<Team> list = new List() { teamA, teamB, teamC, teamD };
如何根据团队层次结构将列表重新排序为正确"的顺序?
How could I reorder a list into the "correct" order based on the team hierarchy?
推荐答案
到目前为止给出的几个解决方案都是正确,并且它们的团队总数至少都是二次方;随着团队数量的增加,它们将变得效率低下.
Several of the solutions given so far are correct, and all of them are at least quadratic in the number of teams; they will be inefficient as the number of teams grows large.
这是一个到目前为止到目前为止(1)线性,(2)更短,(3)更易于理解的解决方案:
Here's a solution which is (1) linear, (2) shorter, and (3) easier to understand than some of the other solutions so far:
static IEnumerable<Team> SortTeams(IEnumerable<Team> teams)
{
var lookup = teams.ToDictionary(t => t.ParentTeam ?? new Team());
var current = teams.Single(t => t.ParentTeam == null);
do
yield return current;
while (lookup.TryGetValue(current, out current));
}
这会按照您想要的顺序产生相反的顺序,因此,如果您希望以其他顺序来排列它,则在通话结束时放置一个Reverse:
This produces the sequence in the reverse of the order you want, so put a Reverse on the end of the call if you want it in the other order:
Console.WriteLine(String.Join(" ", SortTeams(teams).Reverse().Select(t => t.Name)));
虚拟"团队之所以存在,是因为字典不允许键为空.
The "dummy" team is there because a dictionary does not allow a key to be null.
这篇关于在C#中,如何排序该项目列表中哪个项目更大?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!