Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 978
tony Avatar asked Jun 16 '17 18:06

tony


People also ask

Can you use Linq on IEnumerable?

All LINQ methods are extension methods to the IEnumerable<T> interface. That means that you can call any LINQ method on any object that implements IEnumerable<T> . You can even create your own classes that implement IEnumerable<T> , and those classes will instantly "inherit" all LINQ functionality!

Can I convert IEnumerable to List?

In C#, an IEnumerable can be converted to a List through the following lines of code: IEnumerable enumerable = Enumerable. Range(1, 300); List asList = enumerable. ToList();

Is IEnumerable faster than List C#?

IEnumerable is conceptually faster than List because of the deferred execution. Deferred execution makes IEnumerable faster because it only gets the data when needed. Contrary to Lists having the data in-memory all the time.

What is the difference between ICollection and IEnumerable?

An ICollection is another type of collection, which derives from IEnumerable and extends it's functionality to modify (Add or Update or Remove) data. ICollection also holds the count of elements in it and we does not need to iterate over all elements to get total number of elements.


1 Answers

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());
like image 74
Deadzone Avatar answered Dec 09 '22 01:12

Deadzone