【问题标题】:How to convert IOrderedEnumerable<T> to PagedList<T> which uses OrderBy and ThenBy?如何将 IOrderedEnumerable<T> 转换为使用 OrderBy 和 ThenBy 的 PagedList<T>?
【发布时间】:2011-04-22 13:18:47
【问题描述】:

假设您有一个 Product 类,其成员声明为嵌套类型 ProductFeature:

public class Product {
   public ProductFeature ProductID {get;set;}
   public ProductFeature ProductName {get;set;}
}

public class ProductFeature {
   public int FeatureID {get;set;}
   public string FeatureName {get;set;}
}

在某个地方,您有一种方法可以将所有产品加载为PagedList&lt;Product&gt;

var list = db.GetProductList();//returns PagedList<Product>:

现在您要过滤并应用一些OrderByThenBy

var sorted = model.Products.OrderBy(x => x.ProductName).ThenBy(x=>x.ProductID);

sorted 的结果可以被视为IEnumerable&lt;T&gt;IOrderedEnumerable&lt;T&gt;

问题是当我们尝试将sorted 转换回PagedList&lt;Product&gt;List&lt;Product&gt; 时。

base {System.SystemException}: {"At least one object must implement IComparable."}
Message: "At least one object must implement IComparable."

有什么方法可以再次将sorted 转换为List

【问题讨论】:

    标签: linq c#-4.0 sql-order-by pagedlist


    【解决方案1】:

    您的第一个问题是Product.ProductNameProduct.ProductIDProductFeature 的实例,它没有实现IComparable,因此当您尝试枚举@987654327 的结果时您的OrderByThenBy 失败@。这显然是异常消息告诉您的内容。

    您的第二个问题是,当您说“将sorted 转换回PagedList&lt;Product&gt;List&lt;Product&gt;”时,您没有告诉我们您所说的“转换”是什么意思。但是,我怀疑您的意思实际上可以通过使 ProductNameProductID 实现 IComparable 的实例来解决。

    【讨论】:

    • 不错!这正是问题所在!我想我将使用例如:x.ProductName.FeatureName in order by
    • @Junior Mayhé:这将是一个可以接受的解决方案。更好的选择可能是让ProductFeature 实现IComparable&lt;string&gt; 并让CompareToFeatureName 的各个值上返回CompareTo 的结果。
    猜你喜欢
    • 1970-01-01
    • 2014-02-05
    • 2012-10-22
    • 2016-02-29
    • 2019-06-13
    • 2010-11-18
    • 2012-01-22
    • 1970-01-01
    • 2011-06-13
    相关资源
    最近更新 更多