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.
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!
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();
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.
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With