【问题标题】:Syntax error when performing OrderBy<T> on an IEnumerable List在 IEnumerable 列表上执行 OrderBy<T> 时出现语法错误
【发布时间】:2010-06-23 18:11:15
【问题描述】:

我收到的错误信息是:

至少一个对象必须实现 IComparable

导致这种情况的代码如下:

private static IEnumerable<Result> setOrderBy(IEnumerable<Result> value, string order)
{
    if (order.Equals("ASC"))
    {
        //value = value.OrderBy(c => c, new SearchService.ResultComparer<Attribute>());
        value = value.OrderBy<Result>(o => o.StringAttributes.Where(p => p.AttributeName == "Title"), new SearchService.ResultComparer<Attribute>());
        //value = value.OrderBy(o => o.StringAttributes.Where(p => p.AttributeName == "Title"), new SearchService.ResultComparer<AttributeItem>()));
    }
    if (order.Equals("DESC"))
    {
        value = value.OrderByDescending(c => c, new SearchService.ResultComparer<Attribute>());
        //value = value.OrderByDescending(o => o.StringAttributes.Where(p => p.AttributeName == "MatterName"));
    }
    return value;
}

一点背景: 在我的 MVC2 应用程序中,我在我的搜索控制器中执行搜索。当我将结果发送到结果视图时,我试图按字母顺序、升序或降序对结果进行排序。 然而,当我写出为我的结果对象设置 OrderBy 属性的逻辑时,我在代码下方看到一条弯曲的红线(如 VS2008 中所示)。由于某种原因,该方法不喜欢我尝试对其进行排序的数据模型。每个 Result 对象都有各种属性,其中一个是字符串类型的属性列表(因此命名为 StringAttributes)我的结果记录。

请帮忙!

【问题讨论】:

  • 你在哪一行得到错误?
  • 顺便说一句,最好使用if() {} else if() { },因为只有一个可能
  • 谢谢。通常当我编程时,我先让它工作,然后重构。一定喜欢敏捷编程吧?

标签: c# linq asp.net-mvc-2 ienumerable sql-order-by


【解决方案1】:

我认为您需要在选择Attribute 的地方使用First()Single 而不是Where() 进行订购。目前,您要求 OrderBy 使用 IEnumerable&lt;Attribute&gt; 而不是特定属性来计算订单。

value = value.OrderBy<Result>(o => o.StringAttributes.Single(p => p.AttributeName == "Title"), new SearchService.ResultComparer<Attribute>());

value = value.OrderBy<Result>(o => o.StringAttributes.First(p => p.AttributeName == "Title"), new SearchService.ResultComparer<Attribute>());

【讨论】:

  • 我已经尝试过您的方法并得到相同的波浪线,它告诉我:“无法从用法中推断出方法的类型参数。尝试显式指定参数”我已删除类型后缀OrderBy 给我留下: value.OrderBy(o => o.StringAttributes.First(p => p.AttributeName == "Title"), new SearchService.ResultComparer());但是这不起作用:s 如果我只是传入模型,我不会收到错误,但我不会使用正确的标准进行排序。即 value.OrderBy(o => o, new SearchService.ResultComparer());
  • StringAttributes 集合的类型是什么?是 IEnumerable 还是其他?您需要确保类型与您传入的 IComparer 的类型匹配。如果 StringAttributes 是 IEnumerable 那么您需要传入 IComparer
  • StringAttributes 是一个列表。每个 Attribute 有 2 个属性:AttributeName 和 List 每个 AttributeItem 是 Attribute 可能值的列表。对于每个结果,AttributeItems 应该只是与该记录关联的值。
  • SearchService.ResultComparer() 是否实现了 IComparer
  • SearchService.ResultComparer 确实如此。下面的签名: public class ResultComparer : IComparer { }
猜你喜欢
  • 2023-03-14
  • 2013-10-07
  • 1970-01-01
  • 2014-12-03
  • 1970-01-01
  • 2010-09-07
  • 1970-01-01
相关资源
最近更新 更多