c# - 如何使用 linq 将 IEnumerable 转换为 Collection

标签 c# linq collections type-conversion

我正在使用 ProductViewModel 中的产品填充部分 View 。当模型回来时,我们有...

var viewModel = _productAgent.GetProductsByCatalog(catalogId);

viewModel 是 ProductViewModel 的集合

我正在使用 linq 将集合的大小限制为前 10 个产品 orderby createDate desc 像这样......
var newList = (from p in viewModel
           //from pf in p.DomainObjectFields
           select p).Distinct().OrderByDescending(d => d.CreateDate).Take(10);

我尝试加载部分...
return PartialView("_ProductGrid", viewModel);

问题是 newList 是 IEnumerable 它需要是一个集合,我不知道如何转换它,或者我是否采取了正确的方法。

最佳答案

您可以使用扩展方法 .ToList() , .ToArray() , 等等。

var newList = viewModel
    .Distinct()
    .OrderByDescending(d => d.CreateDate)
    .Take(10)
    .ToList();

更新

如果要转换 IEnumerable<T>Collection<T>您可以使用类的构造函数的重载Collection<T>像这样:
Collection<ProductViewModel> newList = new Collection<ProductViewModel>(viewModel
    .Distinct()
    .OrderByDescending(d => d.CreateDate)
    .Take(10)
    .ToList());

关于c# - 如何使用 linq 将 IEnumerable 转换为 Collection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44595802/

相关文章:

c# - Owin 外部登录操作 "Challenge"始终重定向到登录页面

c# - LINQ、迭代器、选择和投影

c# - 这在 LINQ 中可能吗?

java - 泛型类在 Java 6 中编译,但在 Java 7 中不编译

c# - 工厂应该跟踪创建的 IDisposable 对象吗?

c# - 使用 AutoResetEvent 暂停/恢复线程

c# - PDF 中的 iTextSharp target=_blank

c# - 在c#中对多个元素的结构数组进行排序

C# MongoDB 和更新项目列表

Scala - 从多维数组中安全地获取元素