Search code examples
linqc#-4.0sql-order-bypagedlist

How to convert IOrderedEnumerable<T> to PagedList<T> which uses OrderBy and ThenBy?


suppose you have a class Product, with members that are declared as nested type 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;}
}

and somewhere you have a method to load all products as a PagedList<Product>:

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

now you want to filter and apply some OrderBy and ThenBy:

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

the result of sorted can be treated as IEnumerable<T> and also IOrderedEnumerable<T>.

the problem is when we try to convert sorted back to PagedList<Product>, or List<Product>.

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

Any way to convert sorted as a List again?


Solution

  • Your first problem is that Product.ProductName and Product.ProductID are instances of ProductFeature which does not implement IComparable and therefore your OrderBy and ThenBy fail when you try to enumerate over the results of sorted. This is clearly what the exception message is telling you.

    Your second problem is that you didn't tell us what you mean by "convert" when you say "convert sorted back to PagedList<Product>, or List<Product>." However, I suspect whatever you mean will actually be resolved by making ProductName and ProductID instances of something that implement IComparable.