使用list属性的Linq订单列表

时间:2014-10-23 15:53:17

标签: c# linq

如果我有足球队的名单,并且每个队都包含一个列表匹配。如果每场比赛都有进球的属性,我如何订购足球队的名单,以便按照最新比赛中得分最多的顺序进行排序,之后是比赛,依此类推? 比赛次数未知。

我无法弄清楚linq并且我没有太多运气调查动态linq

非常感谢

匹配的数量总是相同的,理论上没有最大值,尽管预计它会小于20是合理的。如果目标数量相同,它将按字母顺序使用团队名称。 / p>

2 个答案:

答案 0 :(得分:1)

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
}

答案 1 :(得分:1)

递归似乎没有必要。这是一种迭代方法。

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