LINQ Group由几个带有IComparable异常的值组成

时间:2013-04-28 23:16:35

标签: c# linq group-by

我有可能的值列表

|团队| |年|胜| “Team1”2014 7 “Team2”2015 9 “Team1”2014 8

我想得到结果

|团队| |年|胜| “Team1”2014 15 “Team2”2015 9

我尝试这样做,但我得到至少有一个对象必须实现Icomparable

 gameResults =
                    gameResults.GroupBy(t => new{t.ContendersName, t.Year})
                    .OrderBy(g => g.Key)
                    .Select(g => new PivotTeamResult()
                       {
                           ContendersName = g.Key.ContendersName,
                           Year = g.Key.Year,
                           Wins = g.Sum(x => x.Wins)                          

                       }).ToList();

我将IComparable实现为

public int CompareTo(object obj)         {

        PivotTeamResult teamResult = (PivotTeamResult)obj;

        if (this.ContendersName == teamResult.ContendersName)
        {
              return this.Year.CompareTo(teamResult.Year);
        }

        return teamResult.ContendersName.CompareTo(this.ContendersName);
    }

我如何才能得到正确的结果?

3 个答案:

答案 0 :(得分:1)

我不确定,但我认为你的问题在于OrderBy而不是GroupBy语句。 正如我所看到的那样,您正在尝试订购一个无法比较且无法排序的组密钥。

也许这会奏效:

  gameResults =
                gameResults.GroupBy(t => new{t.ContendersName, t.Year})
                .OrderBy(g => g.Key.ContendersName)
                .Select(g => new PivotTeamResult()
                   {
                       ContendersName = g.Key.ContendersName,
                       Year = g.Key.Year,
                       Wins = g.Sum(x => x.Wins)                          

                   }).ToList();

答案 1 :(得分:1)

此处您已为PivotTeamResult实施了比较器,但在OrderBy子句中您正在比较匿名类型{t.ContendersName, t.Year},因此您可以直接执行订单:

gameResults =
                gameResults.GroupBy(t => new{t.ContendersName, t.Year})
                .OrderBy(g => g.Key.ContendersName)
                .ThenBy(g => g.Key.Year)
                .Select(g => new PivotTeamResult()
                   {
                       ContendersName = g.Key.ContendersName,
                       Year = g.Key.Year,
                       Wins = g.Sum(x => x.Wins)                          

                   }).ToList();

答案 2 :(得分:0)

由于(PivotTeamResult)obj,您的CompareTo方法不够安全; 我认为这就是你所需要的:

gameResults = gameResults.GroupBy(t => new {t.ContendersName, t.Year}).Select(
                   g => new PivotTeamResult()
                   {
                       ContendersName = g.Key.ContendersName,
                       Year = g.Key.Year,
                       Wins = g.Sum(x => x.Wins)                          

                   }).ToList();

如果你想使用OrderBy,Sort或其他使用对象比较的方法,必须实现IComparable,在这种情况下它不是必需的