如何使用linq将IEnumerable转换为Collection

ton*_*ony 0 c# linq collections type-conversion

我使用ProductViewModel中的产品填充部分视图.当模型回来时我们有......

var viewModel = _productAgent.GetProductsByCatalog(catalogId);
Run Code Online (Sandbox Code Playgroud)

viewModel是ProductViewModel的集合

我正在使用linq将集合的大小限制为前10个产品,因为createDate desc就像这样......

var newList = (from p in viewModel
           //from pf in p.DomainObjectFields
           select p).Distinct().OrderByDescending(d => d.CreateDate).Take(10);
Run Code Online (Sandbox Code Playgroud)

我尝试加载部分...

return PartialView("_ProductGrid", viewModel);
Run Code Online (Sandbox Code Playgroud)

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

Dea*_*one 12

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

var newList = viewModel
    .Distinct()
    .OrderByDescending(d => d.CreateDate)
    .Take(10)
    .ToList();
Run Code Online (Sandbox Code Playgroud)

更新

如果你想转换IEnumerable<T>Collection<T>你可以使用类的构造函数的重载,Collection<T>如下所示:

Collection<ProductViewModel> newList = new Collection<ProductViewModel>(viewModel
    .Distinct()
    .OrderByDescending(d => d.CreateDate)
    .Take(10)
    .ToList());
Run Code Online (Sandbox Code Playgroud)

  • 如果想保持懒惰,您还可以使用 linq 扩展方法 `AsEnumerable`。 (2认同)