应用'GroupBy'LINQ子句时出错:“至少有一个对象必须实现IComparable。”

时间:2014-09-02 02:23:20

标签: c# linq

我尝试按用户名分组自定义实体对象的集合,然后按位置分组。对于特定用户,当我到达第二个' groupby'时,我总是收到错误:

"至少有一个对象必须实现IComparable。"

相关用户有一个用户名" #gill' n"。当我执行第一个" GroupBy"在该suername上,它返回一个匿名类型Count = 6,这是正确的,但该类型中的元素数是8,其中最后两个为null。我认为最后两个空值导致我的问题,但我无法弄清楚他们来自哪里。

     List<CheatSheet> allRelevantCheatSheets = CheatSheet.GetCheatSheets(Globals.FOOString)   // only grade football sheets
                                              .Where(x => x.Username != String.Empty)      // only grade user sheets
                                              .Where(x => x.SeasonCode == currrentFOOSeason)  // only grade sheet for the current season
                                              .Where(x => x.LastUpdated < kickoffDate)         // only grade sheets before the kickoff date
                                              .Where(x => x.Positions.Count == 1)    // only grade single-position sheets
                                              .Where(x => (bool)x.MappedProperties[CSProperty.PPRLeague.ToString()] == false) // only grade standard socring sheets
                                              .ToList();

  foreach (var userSheetGroup in allRelevantCheatSheets.GroupBy(x => x.Username).OrderBy(x => x.Key))
  {

    int newCheatSheetID = 0;
    groupCounter++;

    // then group userSheets by position
    foreach (var targetUserPositionalSheetGroup in userSheetGroup.GroupBy(x => x.Positions[0]).OrderBy(x => x.Key))
    {
      // finally limit the type of sheet returned to only 1 (the latest one ordered by date), must cast to list in order to avoid casting error, then take first item
      CheatSheet userTopPositionSheet = (CheatSheet)targetUserPositionalSheetGroup.OrderBy(x => x.CheatSheetID).OrderBy(x => x.Positions[0]).OrderByDescending(x => x.LastUpdated).Take(1).ToList()[0];
      newCheatSheetID = ArchiveCheatSheet(userTopPositionSheet);
      if (newCheatSheetID == 0)
      {
        errorCounter++;
      }
      else
      {
        sheetCounter++;

        ArchiveCheatSheetItems(userTopPositionSheet.CheatSheetID, newCheatSheetID);
      }
    }
  }

GroupBy Error

1 个答案:

答案 0 :(得分:2)

首先,null值是红色鲱鱼。 .NET中集合的内部实现通常似乎具有2的幂的基础元素计数,可能在集合操作操作中维持amortized time。计数为6是正确的。

其次,如果x.Positions[0]的类型没有实现IComparable,并且找不到默认的比较器,那么由于.OrderBy(x => x.Key),您将得到指定的异常,因为没有定义如何对元素进行排序。如果是这种情况,请使用双参数扩展方法(如果计算this,则为三参数),以允许您指定要使用的IComparerhttp://msdn.microsoft.com/en-us/library/bb549422(v=vs.110).aspx。或者,如果您拥有x.Positions[0]类型的所有权,请对其进行修改以实施IComparable