tony
tony

Reputation: 305

How do I convert IEnumerable to Collection with linq

I am populating a partial view with product from my ProductViewModel. When the model comes back we have...

var viewModel = _productAgent.GetProductsByCatalog(catalogId);

viewModel is a Collection of ProductViewModel

I am using linq to limit the size of the collection to the top 10 products orderby createDate desc like so...

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

and I try to load the partial...

return PartialView("_ProductGrid", viewModel);

The problem is newList is IEnumerable It needs to be a collection and I do not know how to convert it OR if I'm taking the correct approach.

Upvotes: 9

Views: 26110

Answers (2)

tvand08
tvand08

Reputation: 9

You could try newList.toList();

Upvotes: -3

Deadzone
Deadzone

Reputation: 814

You can use the extension methods .ToList(), .ToArray(), etc.

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

Update

If you want to convert an IEnumerable<T> to Collection<T> you can use the overload of the constructor of the class Collection<T> like this:

Collection<ProductViewModel> newList = new Collection<ProductViewModel>(viewModel
    .Distinct()
    .OrderByDescending(d => d.CreateDate)
    .Take(10)
    .ToList());

Upvotes: 24

Related Questions