使用list属性的Linq顺序列表



如果我有一个足球队的列表,并且每支球队都包含一个列表匹配项。如果每场比赛都有进球数,我如何排序足球队名单,使其按最近一场比赛中进球数最多的球队排序,然后是前一场比赛,依此类推?匹配的数量未知。

我搞不清linq,我在研究动态linq 方面运气不好

非常感谢

比赛次数总是一样的,理论上没有最大值,尽管可以合理地预计会少于20场。如果进球数相同,将按字母顺序使用球队名称。

Linq本身不进行递归。为了进行递归搜索,您可能需要定义一个自定义比较器,然后将其传递给OrderBy。如果看不到实际结构,伪代码将是:

N = 1
while(true)
{
   if L has less than N matches
       if R has less than matches
           return L.Name.CompareTo(R.Name)  // order by team name
       else
           return 1 // R has more matches
   if R has less than matches // L has more matches
        return -1
   compare Nth match of each team
   if equal
       N = N + 1; 
   else
       return compare result
}

递归似乎没有必要。这里有一个迭代方法。

void Main() {
    var teams = CreateTeams().ToArray();
    int games = teams.Min(t => t.Games.Count);
    var ordered = teams.OrderBy(team => 0);
    for (int i = games - 1; i >= 0; i--) {
        var captured = i; // the value of i will change, so use this capturing variable, 
        ordered = ordered.ThenByDescending(team => team.Games[captured].Points);
    }
    ordered = ordered.ThenBy(team => team.Name);
    foreach (var team in ordered) {
        Console.WriteLine("{0} {1}", team.Name, string.Join(", ", team.Games.Select(game => game.Points)));
    }
}
IEnumerable<Team> CreateTeams() { 
    yield return (new Team("War Donkeys", 1, 2, 3));
    yield return (new Team("Fighting Beavers", 2, 2, 3));
    yield return (new Team("Angry Potatoes", 2, 1, 3));
    yield return (new Team("Wispy Waterfalls", 3, 2, 1));
    yield return (new Team("Frisky Felines", 1, 2, 3));
}
class Team {
    public string Name { get; set; }
    public IList<Game> Games { get; set; }
    public Team(string name, params int[] points) {
        this.Name = name;
        this.Games = points.Select(p => new Game { Points = p }).ToArray();
    }
}
class Game {
    public int Points { get; set; }
}

输出为

Fighting Beavers 2, 2, 3
Frisky Felines 1, 2, 3
War Donkeys 1, 2, 3
Angry Potatoes 2, 1, 3
Wispy Waterfalls 3, 2, 1

最新更新