I am using an external library thats returns a IEnumerable
. After I have recieved them I would like to add some models to the end. That only seems possible when using an IList
or some other collection. So when i'm trying to convert the IEnumerable
to a list using the .ToList()
method it returns an IEnumerable
. That's not the what I expected? Am I using .ToList()
correct? Or what else would solve my problem?
This is my code i have so far:
IList<Models.Browser.Language> languages = GetLanguages(dateDrom, dateTo).ToList();
IList<Models.Browser.Language> primaryItems = languages.Take(10);
This last line produces an error saying: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<Bogus.Models.Browser.Language>' to 'System.Collections.Generic.IList<Bogus.Models.Browser.Language>'. An explicit conversion exists (are you missing a cast?)
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<Bogus.Models.Browser.Language>' to 'System.Collections.Generic.IList<Bogus.Models.Browser.Language>'. An explicit conversion exists (are you missing a cast?)
Thanks in advance!
The value of languages
is a reference to a List<>
, but then you're calling Take(10)
on that, which doesn't return a list.
Just move your ToList()
call:
IEnumerable<Models.Browser.Language> languages = GetLanguages(dateDrom, dateTo);
IList<Models.Browser.Language> primaryItems = languages.Take(10).ToList();
Or just do it in one call:
var primaryItems = GetLanguages(dateDrom, dateTo).Take(10).ToList();
Also, this isn't quite correct:
After I have recieved them I would like to add some models to the end.
An alternative is to use Concat
. For example:
var items = GetLanguages(dateDrom, dateTo).Take(10).Concat(fixedItems);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.