如何将 IOrderedEnumerable转换为到 PagedList它使用 OrderBy 和 ThenBy?
假设您有一个 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
:
var list = db.GetProductList();//returns PagedList<Product>:
现在您想要过滤并应用一些 < code>OrderBy 和 ThenBy
:
var sorted = model.Products.OrderBy(x => x.ProductName).ThenBy(x=>x.ProductID);
排序的结果可以视为 IEnumerable
并且也IOrderedEnumerable
。
问题是当我们尝试将 sorted
转换回 PagedList
或 List
时。
base {System.SystemException}: {"At least one object must implement IComparable."}
Message: "At least one object must implement IComparable."
有什么方法可以将 sorted
再次转换为 List
吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的第一个问题是
Product.ProductName
和Product.ProductID
是ProductFeature
的实例,它没有实现IComparable
和因此,当您尝试枚举sorted
的结果时,您的OrderBy
和ThenBy
会失败。这显然是异常消息告诉您的内容。您的第二个问题是,当您说“将
sorted
转换回PagedList
或List
时,您没有告诉我们“转换”的含义。 ;产品>
。”但是,我怀疑您的意思实际上可以通过创建实现IComparable
的实例来解决。Your first problem is that
Product.ProductName
andProduct.ProductID
are instances ofProductFeature
which does not implementIComparable
and therefore yourOrderBy
andThenBy
fail when you try to enumerate over the results ofsorted
. 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 toPagedList<Product>
, orList<Product>
." However, I suspect whatever you mean will actually be resolved by makingProductName
andProductID
instances of something that implementIComparable
.